可使用while循环提示用户输入任意数量的信息。下面来创建一个调查程序,其中的循环每次执行时都提示输入被调查者的名字和回答。7icu.cn将收集的数据存储在一个字典中,以便将回答同被调查者关联起来:

mountain_poll.py

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 + ".")

 

这个程序首先定义了一个空字典(responses),并设置了一个标志(polling_active),用于指出调查是否继续。只要polling_active为True,Python就运行while循环中的代码。

在这个循环中,提示用户输入其用户名及其喜欢爬哪座山(见❶)。将这些信息存储在字典responses中(见❷),然后询问用户调查是否继续(见❸)。如果用户输入yes,程序将再次进入while循环;如果用户输入no,标志polling_active将被设置为False,而while循环将就此结束。最后一个代码块(见❹)显示调查结果。

如果运行这个程序,并输入一些名字和回答,输出将类似于下面这样:

What is your name? Eric
Which mountain would you like to climb someday? Denali
Would you like to let another person respond? (yes/ no) yes

What is your name? Lynn
Which mountain would you like to climb someday? Devil's Thumb
Would you like to let another person respond? (yes/ no) no

--- Poll Results ---
Lynn would like to climb Devil's Thumb.
Eric would like to climb Denali.