Home > other >  repeated response in filling a dictionary with user input
repeated response in filling a dictionary with user input

Time:10-23

I am trying to create a poll where users can input their name and mountain then when the poll is complete, the code will print "Name would like to climb mountain." However, the mountain that is printed is always the mountain that is input by the last user. May I know how to rectify such that it prints diff mountains for different users? Thanks.

My code:

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

Results:

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.

CodePudding user response:

you have a typo , in last 2 lines, change reponse

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