简体   繁体   中英

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]? ')

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM