How can I limit the user input to only integers in Python

How can I limit the user input to only integers in Python

Your code would become:

def Survey():

    print(1) Blue)
    print(2) Red)
    print(3) Yellow)

    while True:
        try:
            question = int(input(Out of these options(1,2,3), which is your favourite?))
            break
        except:
            print(Thats not a valid option!)

    if question == 1:
        print(Nice!)
    elif question == 2:
        print(Cool)
    elif question == 3:
        print(Awesome!)
    else:
        print(Thats not an option!)

The way this works is it makes a loop that will loop infinitely until only numbers are put in. So say I put 1, it would break the loop. But if I put Fooey! the error that WOULD have been raised gets caught by the except statement, and it loops as it hasnt been broken.

The best way would be to use a helper function which can accept a variable type along with the message to take input.

def _input(message, input_type=str):
    while True:
      try:
        return input_type (input(message))
    except:pass

if __name__ == __main__:
    _input(Only accepting integer : , int)
    _input(Only accepting float : , float)
    _input(Accepting anything as string : )

So when you want an integer , you can pass it that i only want integer, just in case you can accept floating number you pass the float as a parameter. It will make your code really slim so if you have to take input 10 times , you dont want to write try catch blocks ten times.

How can I limit the user input to only integers in Python

def func():
    choice = Wrong
    
    while choice.isdigit()==False :
        choice = input(Enter a number: )
        
        if choice.isdigit()==False:
            print(Wrongly entered: )
        else:
            return int(choice)

Leave a Reply

Your email address will not be published. Required fields are marked *