You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 12:36:06