Home > other >  Program won't quit at correct time
Program won't quit at correct time

Time:03-03

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

CodePudding user response:

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

CodePudding user response:

  1. exit is a built-in function. I think it's better to rename the parameter.

  2. 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 break as @rowBee said.

  3. I also think it's simpler and cleaner to update count_all outside 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('...')
  • Related