【问题标题】:repeated response in filling a dictionary with user input在用用户输入填充字典时重复响应
【发布时间】:2021-10-23 09:36:41
【问题描述】:

我正在尝试创建一个民意调查,用户可以在其中输入他们的姓名和山峰,然后当民意调查完成后,代码将打印“姓名想要攀登 。”但是,打印的山总是最后一个用户输入的山。我可以知道如何纠正它为不同的用户打印差异山脉吗?谢谢。

我的代码:

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, reponse in responses.items():
    print(name + " would like to climb " + response + ".")

结果:

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

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

--- Poll Results ---
Amelia would like to climb Matterhorn.
Bobby would like to climb Matterhorn.

【问题讨论】:

    标签: python-3.x dictionary input


    【解决方案1】:

    你有一个错字,在最后两行,更改reponse

    for name, reponse in responses.items():
        print(name + " would like to climb " + reponse + ".")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 2021-07-28
      • 2017-03-22
      • 2015-07-28
      相关资源
      最近更新 更多