Mat Tripodi
Mat Tripodi

Reputation: 23

I need the input to be a number. If nor, display "please enter number" and ask for input again

This is what I want, but for an integer. I am not allowed to use break or continue to exit loops.

# basically I need this, but with an int(input('please enter a number'))

ask = input('Would you like to play Steal or Deal [y|n]? ')


while ask not in ('y', 'n'):

    print ("Please enter either 'y' or 'n'")
    print('')
    ask = input('Would you like to play Steal or Deal [y|n]? ')

Upvotes: 2

Views: 62

Answers (1)

Mureinik
Mureinik

Reputation: 311723

You could try to convert the string to an int and catch the exception:

def is_number(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

ask = input('please enter a number: ')

while not is_number(ask):

    print ("no, a number!")
    print('')
    ask = input('please enter a number: ')

Upvotes: 1

Related Questions