Python Tip: Validating user input as number (Integer)

In most of your Python programs you will want to interact with the end-user by asking questions and retrieving user inputs.

To do so you can use the input() function: e.g.

username=input("What is your username?")

Sometimes you will need to retrieve numbers. Whole numbers (numbers with no decimal place) are called integers. To use them as integers you will need to convert the user input into an integer using the int() function. e.g.

age=int(input("What is your age?"))

This line of code would work fine as long as the user enters an integer. If, by mistake, they enter letters or punctuation signs, the conversion into an integer will fail and generate an exception (error) and the program would stop running.

To validate the user entry and ensure that is a number it is possible to catch this exception when it occurs using the try…except….else block as follows:

try:
    value=int(input("Type a number:"))
except ValueError:
    print("This is not a whole number.")

See how we can use this approach to define our own function (called inputNumber()) to ask for a number. This new function can then be used instead of an input() function whenever we expect the user to enter a whole number. This function uses the try…except….else block within a while loop so that it keeps asking the user to enter a number till the user gets it right.

Final Code:

def inputNumber(message):
  while True:
    try:
       userInput = int(input(message))       
    except ValueError:
       print("Not an integer! Try again.")
       continue
    else:
       return userInput 
       break 
     

#MAIN PROGRAM STARTS HERE:
age = inputNumber("How old are you?")

Did you like this challenge?

Click on a star to rate it!

Average rating 3.6 / 5. Vote count: 22

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!