Python问卷调查所有用户山名输出均为最后输入值的修复问题
问题修复方案
问题根源
你的代码出现该问题是因为输出阶段的变量拼写错误:
- 遍历问卷结果的
for循环中,你把接收山名的变量拼写为reponse(漏写了字母s,正确拼写为response) - 打印语句中调用的是循环外的全局变量
response,这个变量最后一次存储的是最后一位用户输入的山名,因此所有输出的山名都是同一个值。
修正方法
只需要调整输出部分的代码,保持变量拼写一致即可,两种可选修改方式:
- 修正
for循环中的变量拼写,和全局变量名保持一致
# 原错误写法:for name, reponse in responses.items(): for name, response in responses.items(): print(name + " would like to climb " + response + ".")
- 保持
for循环的变量名不变,修改打印语句调用的变量名
for name, reponse in responses.items(): # 原错误写法:print(name + " would like to climb " + response + ".") print(name + " would like to climb " + reponse + ".")
完整修正后代码(保留原英文交互逻辑)
responses = {} # set a flag to indicate that polling is active polling_active = True while polling_active: # prompt for the person's name and response name = input("\nWhat is your name? ") response = input("Which mountain would you like to climb someday? ") # store the response in the dictionary responses[name] = response # find out if anyone else is going to take the poll repeat = input("Would you like to let another person respond? (yes/ no) ") if repeat == 'no': polling_active = False # polling is complete. show the results. print("\n--- Poll Results ---") for name, response in responses.items(): print(name + " would like to climb " + response + ".")
内容的提问来源于stack exchange,提问作者odebear
相关产品推荐
相关产品推荐

