How to check if a user input is an integer in Python?

When using a weakly typed programming language, sometimes is useful to check if the type of the input is the type that we are expecting. This will avoid unpredictable problems with our program.

So, how can we know if the user input is an integer? We use exception handling.

Python and variable types

Python is considered a weakly typed language. Because you don’t need to specify the type of a variable before assigning a value.

For instance:

value = input('Enter an integer number: ')

Even though we specify in the message to enter an integer number, if you execute this line and enter a different type of value, like a string or a float number, the computer will keep executing the code.

As you might find out, it is important to be sure that what the user entered was a number.

Notice that if you try to make an operation with a number, but the value is not a number, you will get an exception.

In this case, we can use exception handling to make sure that the input is an integer.

Python code to check if a user input is an integer

See the Python code below.

valid = True
while valid:
    value = input('Enter an integer number: ')
    try:
        value = int(value)
        valid = False
    except:
        print('Please enter a number')

First, we will use a loop that will ask for an integer number until we confirm that the value entered is indeed a number.

We suppose to use here a loop with postcondition. Unfortunately, Python does not have loops with postconditions. So, we use a trick to make sure that the block of instructions (instructions inside the loop) is executed at least 1 time.

Once we have the value we try to convert that value to an integer. If the value is an integer, the normal execution flow will continue, the variable valid will be equals false, and the loop will finish.

If the variable value holds something different than an integer, you will get an exception. The flow of execution will go to the except block. There, an error message will be printed, and the loop will be executed again.

This type of check is useful when you create a menu for a console application so the user can choose what he/she wants the program to do. If you have a menu, and the user enters something different than the number you are expecting, the program can crash.

Related topics: