user14135601
user14135601

Reputation:

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

Upvotes: 0

Views: 90

Answers (3)

Andres Boullosa
Andres Boullosa

Reputation: 1

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

Upvotes: 0

NMrocks
NMrocks

Reputation: 108

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

Upvotes: 0

Moray
Moray

Reputation: 91

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

Upvotes: 1

Related Questions