简体   繁体   中英

How to exit this while loop

So basically when a user enters 'n' I need it to stop and not ask to enter either y or n, but I can't seem to make it occur, any help?

decider = input('Would you like to play the game? [y/n]? ')

while decider != 'y' :
    if decider == 'n' :
        print('Another time perhaps')
    else :
        print('Please enter either \'y\' or \'n\' ')

    decider = input('Would you like to play the game? [y/n]? ')

Also I understand you can use exit or break but in my exercise that is NOT allowed

You need to ask the user before checking the inputs and before the while loop checks the condition again. Also you need to loop as long as the input is NOT 'n'

decider = ''
while decider != 'n' and decide != 'y' :
    decider = input('Would you like to play the game? [y/n]? ')
    if decider == 'n' :
        print('Another time perhaps')
        break
    elif decider == 'y':
        print('Play again!')
        * insert restart code here*
    else :
        print('Please enter either \'y\' or \'n\' ')

You can solve it adding other constring to the while ald change it when he inset n. I gave you and example below.

import sys

decider = input('Would you like to play the game? [y/n]? ')

while decider != 'y':
    if decider == 'n' :
        print('Another time perhaps')
        sys.exit()
    else :
        print('Please enter either \'y\' or \'n\' ')
        decider = input('Would you like to play the game? [y/n]? ')

Well you were rigth I edit the code to not answer the question again

Try this:

run = True
while run:
    decider = input(•••)
    if decider == "n":
        print(•••)
        run = False
    if decider == "y":
        print(•••)
    else:
        print("Please write either y or n")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM