0
votes

I'm creating a dice poker game and am trying to ask if the user would like to play before continuing with the game and then asking if the player would like to play again after each game.

I am unsure how to allow for incorrect inputs other than Y and N in order to tell the user to enter a correct answer and then loop the input until either is input. I am not allowed to use a break.

play = True
s = input("Would you like to play dice poker [y|n]? ")
if s == "y":
    play = True
elif s == "n":
    play = False
else:
    print("Please enter y or n")
    
while play:

From here onward is the code for my game

This below section is repeated at the end of each game

  again=str(input('Play again [y|n]? '))

    if again == "n":
        play = False
    if again == "y":
        play = True
    else:
        print('Please enter y or n')
1

1 Answers

2
votes

wrap your input in a function that evaluates the user input, if it's not valid, call it recursively as necessary. Example:

def keep_playing():
    valid = 'ny'
    again=str(input('Play again [y|n]? '))
    a = again.lower().strip()  # allow for upper-case input or even whole words like 'Yes' or 'no'
    a = a[0] if a else ''
    if a and a in valid:
        # take advantage of the truthiness of the index: 
        # 0 is Falsy, 1 is Truthy
        return valid.index(a)
    # Otherwise, inform the player of their mistake
    print(f'{again} is not a valid response. Please enter either [y|n].')
    # Prompt again, recursively
    return keep_playing()

while keep_playing():
      print('\tstill playing...')

enter image description here