Lesson
Validation in Python
A PRIMM lesson on input validation, loop conditions, and accepting only sensible values.
Open a shared Python workspace in seconds.
Lesson overview
- Topic
- Validation and testing
- Level
- GCSE
- Learning objective
- Use a validation loop to keep asking for input until it meets a rule.
1.Predict
Example code
age = 0
while age < 11 or age > 16:
age = int(input("Enter an age from 11 to 16: "))
print("Age accepted")- When will the loop stop repeating?
- What do you think happens if someone enters 9 first?
2.Run
Run the code in Paired and test both valid and invalid ages to see how the loop behaves.
3.Investigate
- The loop keeps running while the input is outside the allowed range.
- This is a common validation pattern for classroom programs.
- Why is age given a starting value before the loop begins?
- How do the conditions work together to reject values outside the range?
4.Modify
- Change the accepted range so the program allows ages from 5 to 12.
- Add another message that tells the user when they need to try again.
5.Make
Create a validation loop for a menu choice or a score that only accepts a sensible range.
Extension
Improve the validation so the user also gets a different message for values that are too low and too high.
Need extra support?
Reece offers GCSE & A-Level Computer Science tutoring: reece-tutoring.co.uk