Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

2.8 (1 of 2): Validation: checking input

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

45 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

The age that was "banana"

A student club has a sign-up form. Somebody types "banana" for their age. Somebody leaves the name box empty. Somebody types an age of 400.

The program saves it all. Now the club list is full of wrong data. Good programs stop bad data before it gets in.

Key words

WordWhat it meansExample
ValidationA check that data makes sense before the program uses it.
ValidData that passes the check.an age of 16
InvalidData that fails the check.an age of 400
Presence checkChecks that something was typed.
Length checkChecks how many characters there are.
Range checkChecks that a number is between a lowest and a highest value.
Type checkChecks that the data is the right kind.a whole number
Format checkChecks that the data follows a pattern.an email has an @
Check digitAn extra digit worked out from the other digits. It finds typing mistakes.the last digit of a barcode

The cells students fill in are left blank in this preview.

Validation asks if data makes sense

Validation asks: does this data make sense? It runs when a user types something, before the program uses the data. If the data is invalid, the program asks again.

Validation cannot tell if data is true. An age of 25 passes a range check even if the user is 15.

Try it: presence and length

Code: python
name = ""
password = "abc123"

if len(name) == 0:
    print("Please type your name.")
if len(password) < 8:
    print("The password needs at least 8 characters.")

# Give name and password good values. The messages disappear.

Make a free account to save your work and track your progress.

The checks

CheckThe question it asksExample
PresenceIs there something?A name is not empty
LengthIs it long or short enough?A password has 8 to 20 characters
RangeIs the number between the lowest and highest?An age is from 0 to 120
TypeIs it the right kind of data?An age is a whole number
FormatDoes it follow the pattern?An email has an @ and a dot
Check digitDoes the last number fit the others?The next lesson

The cells students fill in are left blank in this preview.

Try it: type and range

Code: python
text = "250"

if not text.isdigit():
    print("Type check failed: use digits only.")
elif int(text) > 120:
    print("Range check failed: the age is more than 120.")
else:
    print("Age accepted.")

# Try "abc", "16", "-5" and "250".

Make a free account to save your work and track your progress.

Try it: a format check

Code: python
email = "[email protected]"

if "@" in email and "." in email:
    print("The format looks right.")
else:
    print("An email needs an @ and a dot.")

# Try "sam.mail.com".

Make a free account to save your work and track your progress.

Try it: is it a real date?

Code: python
from datetime import datetime

text = "25/12/2026"

try:
    when = datetime.strptime(text, "%d/%m/%Y")
    print("A real date:", when.strftime("%A %d %B %Y"))
except ValueError:
    print("Please write the date like 25/12/2026.")

# Try "31/02/2026" and "tomorrow". Both fail the check.

Make a free account to save your work and track your progress.

isdigit has limits

Warning

Many people think isdigit() accepts any number. It is True only when every character is a digit. So "16".isdigit() is True, but "-5".isdigit() and "12.5".isdigit() are False, because of the minus sign and the dot. For whole numbers from 0 up, that is what you want.

Quick check: which check?

Have a go

Quick check: which check?

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Extra: Validation is not verification

Note

Verification means checking that data was typed the way the user meant. You type a new password twice, or you read your order back before you pay. Validation asks if data makes sense. Verification asks if it is what you meant.

Ask again until the data is valid

A flowchart: Start, then Input the age, then the question Is it valid, where No leads to Output a message and back to Input the age, and Yes leads to Use the age, then End.A flowchart: Start, then Input the age, then the question Is it valid, where No leads to Output a message and back to Input the age, and Yes leads to Use the age, then End.

Try it: ask until it is valid

Code: python
# These are the answers a user types, one after another.
answers = ["", "abc", "250", "15"]
position = 0

text = answers[position]
while not (text.isdigit() and int(text) <= 120):
    print("Not valid:", text)
    position = position + 1
    text = answers[position]

print("Accepted:", text)

Make a free account to save your work and track your progress.

Watch: the checks at work

Press Play on the short film below. It runs the checks from this lesson on the same examples: an empty name, a short password, the age "250" and the email "sam.mail.com". Then it asks again until an answer is valid. Watch what happens to an age that makes sense but is not true.

Film: validation checks

Validation: checking input

Every scene, as text

  1. Validation is a check that data makes sense before the program uses it. A presence check asks: is there something? name = "" holds nothing, so len(name) == 0 is True and the program prints Please type your name. A length check asks: is it long or short enough? password = "abc123" has 6 characters, so len(password) < 8 is True and it prints The password needs at least 8 characters.
  2. A type check asks: is it the right kind of data? With text = "250", every character is a digit, so not text.isdigit() is False and the type check passes. Then a range check asks: is the number between the lowest and highest? It is an elif, so it runs only because the if was False, and int(text) is only ever given digits. int(text) > 120 is True, so the program prints Range check failed: the age is more than 120.
  3. A format check asks: does it follow the pattern? The program tests if "@" in email and "." in email:. With email = "sam.mail.com", Python asks "@" in email first and gets False, so the whole test is False without looking for the dot, and the else: prints An email needs an @ and a dot.
  4. When data is invalid, a good program asks again. answers holds what a user types, one after another. while not (text.isdigit() and int(text) <= 120): runs its body again while the answer is not valid. "", "abc" and "250" each print Not valid: and the next answer is taken. "15" is valid, so the loop stops and the program prints Accepted: 15.
  5. Myth (false): validation proves the data is true. With text = "25", every character is a digit and 25 is not more than 120, so both checks pass and the else: prints Age accepted. But the user is really 15. Validation asks if data makes sense. Verification asks if it is what you meant, such as typing a new password twice.

Match the rule to the check

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Your turn: build the checks

Build four checks and one loop. present(text) is True if something was typed. Spaces alone do not count. long_enough(password) is True for 8 to 20 characters. age_ok(text) is True if the text is a whole number from 0 to 120: check the type first. email_ok(email) is True if there is exactly one @ and a dot after it. get_age() asks with input until the age is valid. After each bad try it prints exactly: Please type a whole number from 0 to 120. Press Run Tests to check.

Code: python
def present(text):
    # True if the text has something in it. Spaces alone do not count.
    # Hint: text.strip() takes the spaces off both ends.
    return None


def long_enough(password):
    # True if the password has 8 to 20 characters. Both 8 and 20 are allowed.
    return None


def age_ok(text):
    # text is what the user typed. True if it is a whole number from 0 to 120.
    # Check the type first. "abc" and "-5" and "" are not valid.
    return None


def email_ok(email):
    # True if the email has exactly one @ and a dot after the @.
    return None


def get_age():
    # Ask "Age? " with input() again and again until the user types a valid age.
    # Use age_ok(). Give back the age as a whole number.
    # Print "Please type a whole number from 0 to 120." after each bad try.
    return None

Make a free account to save your work, or press Start lab to work through the whole lesson.

Key words crossword

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.