GCSE Python · Lesson 1 of 9

Input validation and robust programs

OCR J277 2.2 / AQA 8525 programming

Validate a whole-number age between 11 and 18.

← All GCSE Python lessons

Validating input

Validation checks that entered data meets stated rules before the program uses it. A range check can reject values outside an allowed interval, while a loop can ask the user to try again. Design tests for both boundaries and values outside the range.

Watch out: Validation is not verification. A value can satisfy the format rules but still be factually wrong.

1 · Learn and predict

Read this worked example. Predict its output, run it in Python 3, and explain how variables change.

def valid_age(text):
    if not text.isdigit():
        return False
    age = int(text)
    return 11 <= age <= 18

for sample in ["15", "-1", "nineteen", "19"]:
    print(sample, valid_age(sample))

2 · Build independently

Validate a whole-number age between 11 and 18. Work from the starter code before comparing with the solution.

Download starter + solution ZIP ↓

For a stretch challenge: add meaningful test data, handle an edge case and explain one design decision.

Reveal reference solution
def valid_age(text):
    if not text.isdigit():
        return False
    age = int(text)
    return 11 <= age <= 18

age_text = input("Enter age (11 to 18): ").strip()
while not valid_age(age_text):
    print("Please enter a whole number between 11 and 18.")
    age_text = input("Age: ").strip()
print("Accepted:", int(age_text))

The reference is one possible approach. Test your own program before comparing.

3 · Debug and explain

Question: Why is checking only age >= 11 insufficient?

Show explanation

It would accept ages above 18, and non-numeric input could crash conversion.

4 · Check your understanding

What is validation for?

5 · Reflect

Explain one test you used, one problem you solved and one improvement you would make.

This records completion only in this browser and does not certify mastery.

Want extra practice? Try interactive Python tracing and debugging questions →