0

So I'm having some trouble with my loop at the beginning of my code asking the user if they want to play. How do I get it to replay the loop if the user types in an invalid response?

Below is what I have so far, but I'm stuck on where to go from here

play = input('Would you like to play the Guess the Number Game [y|n]?')
while play == 'y':
     play = True
if play == 'n':
     print ("No worries... another time perhaps... :)")
     exit()
else:
     print ("Please enter either 'y' or 'n'.")

Taylah369
  • 3
  • 2
  • 3
    Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Sayse Oct 18 '19 at 12:55

4 Answers4

0

I think this is what you want:

break_condition = True
while break_condition:
    play = input('Would you like to play the Guess the Number Game [y|n]?')
    if play == 'y':
        play = True
        break_condition = False

    elif play == 'n':
        print ("No worries... another time perhaps... :)")
        break_condition = False
    else:
        print ("Please enter either 'y' or 'n'.")
0

That can be done with recursion too:

def user_input():
    play = input('Would you like to play the Guess the Number Game [y|n]?')
    if play == 'y':
        print("Play Starting...")
        return True
    elif play == 'n':
        print("No worries... another time perhaps... :)")
        return False
    else:
        user_input()


user_input()
Kostas Charitidis
  • 2,991
  • 1
  • 12
  • 23
0

Define a recursive function for requesting user input that calls itself when input is invalid.

def playFunction():
    play = input('Would you like to play the Guess the Number Game [y|n]?')
    if play == 'y':
         play = True
    if play == 'n':
        play = False
        print ("No worries... another time perhaps... :)")
        return
    else:
         print ("Please enter either 'y' or 'n'.")
         playFunction()
Huw Thomas
  • 317
  • 1
  • 8
0
while True:
    play = input('Would you like to play the Guess the Number Game [y|n]?').lower()
    if play == 'n':
        print ("No worries... another time perhaps... :)")
        break
    elif play == 'y':
        #write your game code here 
    else:
        print ("Please enter either 'y' or 'n'.")