0

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')
Community
  • 1
  • 1
  • 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) – David Zemens Jun 06 '19 at 18:22

1 Answers1

2

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

David Zemens
  • 53,033
  • 11
  • 81
  • 130
  • Can you get a stackoverflow if you give an incorrect input a lot? – doctorlove Jun 06 '19 at 17:49
  • @doctorlove probably, but seems unlikely unless the user is actively trying to do so. – David Zemens Jun 06 '19 at 18:15
  • @doctorlove I can reach the `RecursionError` after 995 invalid attempts. So, hardly seems worth worrying about, but it could be addressed by tweaking the code with some sort of counter to force a `False` return value when you reach some arbitrary number of invalid attempts. – David Zemens Jun 06 '19 at 18:20