6 Python编程:从入门到实践---用户输入和while循环
函数input()的工作原理
函数input()让程序暂停运行,等待用户输入一些文本。获取用户输入后,Python将其存储在一个变量中,以方便你使用。
求模运算符
%将两个数相除并返回余数
退出循环方法
break&continue
使用用户输入来填充字典
可使用while循环提示用户输入任意数量的信息。下面来创建一个调查程序,其中的循环每次执行时都提示输入被调查者的名字和回答。我们将收集的数据存储在一个字典中,以便将回答同被调查者关联起来
responses = {} # 设置一个标志,指出调查是否继续 polling_active = True while polling_active: # 提示输入被调查者的名字和回答 name = input("\nWhat is your name? ") response = input("Which mountain would you like to climb someday? ") # 将答卷存储在字典中 responses[name] = response # 看看是否还有人要参与调查 repeat = input("Would you like to let another person respond? (yes/ no) ") if repeat == 'no': polling_active = False # 调查结束,显示结果 print("\n--- Poll Results ---") for name, response in responses.items(): print(name + " would like to climb " + response + ".") ================================================ 执行结果 What is your name? 6666 Which mountain would you like to climb someday? ddd Would you like to let another person respond? (yes/ no) yes What is your name? 8888 Which mountain would you like to climb someday? ooo Would you like to let another person respond? (yes/ no) no --- Poll Results --- 6666 would like to climb ddd. 8888 would like to climb ooo.
不积跬步,无以至千里;不积小流,无以成江海。