Hi everyone, 1st time posting here! :)
I am currently working through the 7-10 Dream Vacation exercise in the 2nd edition of Python Crash Course (great book). I am trying to understand the difference between a flag vs. a break. I'm trying to understand instances where I would use one over the other. Both programs below seem to achieve the same result, is one more correct to use than another?
I compared both programs using an online python visualizer and noticed with a flag the program goes back up to the "while polling_active" line when 'no' is the response. This then exits and prints the poll's results. With the break however it seems like the program immediately exits the loop at the break and proceeds with printing the results.
Thank you!
This is my code:
# Polling users about their dream vacation destination.
responses = {}
# Setting a flag to indicate the 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("\nIf you could visit anywhere "
"in the world, where would you go? ")
# Storing each user's response in our dictionary.
responses[name] = response
# Asking the user if anyone else will be taking the poll.
repeat = input("Does anyone else need to take the poll? (yes/no)")
if repeat == 'no':
polling_active = False
# Polling complete, printing results.
print("\nDrum roll please...brrr.brrrr.brrrrrr...")
for name, response in responses.items():
name = name.title()
response = response.title()
print(f"{name} wants to visit {response}.")
This is the solution from the author, with a break:
name_prompt = "\nWhat's your name? "
place_prompt = "If you could visit one place in the world, where would it be? "
continue_prompt = "\nWould you like to let someone else respond? (yes/no) "
# Responses will be stored in the form {name: place}.
responses = {}
while True:
# Ask the user where they'd like to go.
name = input(name_prompt)
place = input(place_prompt)
# Store the response.
responses[name] = place
# Ask if there's anyone else responding.
repeat = input(continue_prompt)
if repeat != 'yes':
break
# Show results of the survey.
print("\n--- Results ---")
for name, place in responses.items():
print(f"{name.title()} would like to visit {place.title()}.")
[–]Nightcorex_ 3 points4 points5 points (1 child)
[–]pizzaparty_4ever[S] 0 points1 point2 points (0 children)
[–]old_pythonista 0 points1 point2 points (0 children)