Validation

Definition

When we accept user input we need to check that it is valid. This checks to see that it is the sort of data we were expecting. There are two different ways we can check whether data is valid.

Method 1: Use a flag variable. This will initially be set to False. If we establish that we have the correct input then we set the flag to True. We can now use the flag to determine what we do next (for instance, we might repeat some code, or use the flag in an if statement).

Method 2: Use try/except. Here, we try to run a section of code. If it doesn’t work (for instance, we try to convert a string to a number, but it doesn’t contain a number) then we run the except block of code.

Types of validation:

Validation technique Meaning
Type check Checking the data type e.g. int, float etc.
Length check Checking the length of a string
Range check Checking if a number entered is between two numbers

Easy example

while True:
    try:
        age = int(input('How old are you? '))
        break
    except ValueError:
        print('Please enter a whole number')

print('Your age is: ' + str(age))
Show/Hide Output
How old are you? asdf
Please enter an whole number
How old are you? 14.5
Please enter an whole number
How old are you? 15
Your age is: 15

Note

This example isn’t easy to understand if it is new to you, but it is the easiest way to ask the user to enter an input and check the input contains an integer.

Syntax

Using a flag

flagName = False
while not flagName:
    if [Do check here]:
        flagName = True
    else:
        print('error message')

Using an exception

while True:
    try:
        [run code that might fail here]
        break
    except:
        print('This is the error message if the code fails')

print('run the code from here if code is successfully run in the try block of code above')

Examples

Example 1 - Check if input contains digits using a flag

validInteger = False

while not validInteger:
    age = input('How old are you? ')
    if age.isdigit():
        validInteger = True
    else:
        print('You must enter a valid number')

print('You are ' + str(age))
Show/Hide Output
How old are you? asdf
You must enter a valid number
How old are you? 15.0
You must enter a valid number
How old are you? 18.2
You must enter a valid number
How old are you? -3
You must enter a valid number
How old are you? 15
You are 15

Note

This has the same result as the easy example above which makes use of try/except to do the same thing.

Note

This example is fine for checking integers, but will not check floating point numbers or negative numbers. Use try/except to do this - see examples below.

Example 2 - A range and type check using a flag and exception

isTeenager = False

while not isTeenager:
    try:
        age = int(input('How old are you? '))
        if age >= 13 and age <= 19:
            isTeenager = True
    except:
        print('You must enter a valid number between 13 and 19')

print('You are a teenager aged ' + str(age))
Show/Hide Output
How old are you? asdf
You must enter a valid number between 13 and 19
How old are you? -3
How old are you? 15.2
You must enter a valid number between 13 and 19
How old are you? 12
How old are you? 14
You are a teenager aged 14

Example 3 - A length check using a flag

isLongEnough = False

while not isLongEnough:
    password = input('Enter password at least 5 characters: ')
    if len(password) >= 5:
        isLongEnough = True
    else:
        print('Password entered is too short')

print('Your password entered is: ' + password)
Show/Hide Output
Enter password at least 5 characters: asdf
Password entered is too short
Enter password at least 5 characters: 1234
Password entered is too short
Enter password at least 5 characters: ad4fgj
Your password entered is: ad4fgj

Example 4 - Multiple validations using a flag

isFourDigitPassword = False
oldPassword = '2154'

while not isFourDigitPassword:
    password = input('Enter a new PIN: ')
    if len(password) == 4 and password.isdigit() and password != oldPassword:
        isFourDigitPassword = True
    else:
        print('Your PIN must be 4 digits and not the same as your old PIN')

print('Your PIN entered is: ' + password)
Show/Hide Output
Enter a new PIN: asdf
Your PIN must be 4 digits and not the same as your old PIN
Enter a new PIN: 2154
Your PIN must be 4 digits and not the same as your old PIN
Enter a new PIN: 12345
Your PIN must be 4 digits and not the same as your old PIN
Enter a new PIN: 123
Your PIN must be 4 digits and not the same as your old PIN
Enter a new PIN: 1234
Your PIN entered is: 1234

Example 5 - Check for a float using an exception

while True:
    try:
        height = float(input('What is your height in cm? '))
        break
    except ValueError:
        print('Please enter a number')

print('Your height is: ' + str(height))
Show/Hide Output
What is your height in cm? 5 foot 4 inches
Please enter a number
What is your height in cm? 162.5
Your height is: 162.5

Example 6 - A function to get an integer from the user

def getInteger(message):
    while True:
        try:
            userInt = int(input(message))
            return userInt
        except ValueError:
            print('You must enter an integer')


age = getInteger('What is your age? ')
players = getInteger('How many players in the game? ')
Show/Hide Output
What is your age? fifteen
You must enter an integer
What is your age? 15
How many players in the game? two
You must enter an integer
How many players in the game? 2.2
You must enter an integer
How many players in the game? 2

Note

You can reuse this function in your own code as an easy way to get an integer from a user.

Example 7 - A function to get a floating point number from the user

def getFloat(message):
    while True:
        try:
            userFloat = float(input(message))
            return userFloat
        except ValueError:
            print('You must enter a number')


height = getFloat('How tall are you? ')

print('Your height is: ' + str(height))
Show/Hide Output
How tall are you? 1 meter 60
You must enter a number
How tall are you? 1.60
Your height is: 1.6

Key points

Warning

In general we don’t use while True: and break as this can end up creating poor quality code or infinite loops. In the case of try/except, this is acceptable for getting user input and validation.