'Program won't quit at correct time
I am trying to ask the user whether they want to see a book, and then asking if they know the story. I the want to then tell the user how many stories they know out of how many attempts. Unfortunately the program won't quit at the correct time.
# Set count list to zero
count_y = 0
count_all = 0
# Asking the user whether they want to see a book
exit = False
while not exit:
user_input = input('Enter s to see a book and q to quit: ')
if user_input == 'q':
exit = True
elif user_input == 's':
show_book()
# I am trying to tell the user how many stories they knew out of their total attempts.
user_answer = input('Did you know the stories? Press Y or N: ')
if user_answer == 'y':
count_y = count_y + 1
elif user_answer == 'y' or 'n':
count_all = count_all + 1
# print the result to the user.
print('You knew',(count_y), 'out of', (count_all), 'stories .')
Solution 1:[1]
Your code keeps running because you just set exit to true and don't set a break or continue underneath (Your program will finish this iteration). You can also put the code below in the elif block (if that works for you) I think there is also a piece missing in the middle so I can't tell 100%.
if user_input == 'q':
break
Solution 2:[2]
exitis a built-in function. I think it's better to rename the parameter.In the current script, you're asking the user if the story is known even when "q" is choose. You can rewrite it as below, or simply puts a
breakas @rowBee said.I also think it's simpler and cleaner to update
count_alloutside the if-statement.
count_y = 0
count_all = 0
to_exit = False
while not to_exit:
user_input = input('...')
if user_input == 'q':
to_exit = True
elif user_input == 's':
show_book()
count_all += 1
user_answer = input('...')
if user_answer == 'y':
count_y += 1
print('...')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Filippe O. Gonçalves |
