Defensive Design
Input validation is a defensive design technique: it checks what a user has typed before the program uses it. The check compares the input with rules you set, such as a number falling inside an allowed range, or an answer matching one of the options offered. If the input breaks a rule, the program refuses it and asks again.
Validation is the usual way to deal with invalid input, because users mistype, leave boxes empty or try to misuse a program. A value of the wrong type or wildly out of range can give a wrong result or stop the program with a run-time error, so checking first keeps the program running with sensible data.
A common pattern is a loop that reads the input, tests it, and only lets the program move on once the value passes. Each time the rule is broken, a short message explains it and the question is asked again.
tickets = int(input("How many tickets? "))
while tickets < 1 or tickets > 6:
print("Enter a whole number from 1 to 6.")
tickets = int(input("How many tickets? "))
print("Booking accepted for", tickets, "tickets")Output when the user types 0, 4:
How many tickets? 0
Enter a whole number from 1 to 6.
How many tickets? 4
Booking accepted for 4 ticketsThe rule here is a whole number of tickets from 1 to 6. Typing 0 makes the condition true, so the loop repeats and the question is asked again; typing 4 makes it false, so the loop ends and the booking goes through. The loop only compares numbers, though: if the user types text, int() cannot convert it, so the program still stops with an error.
Validation can show that data is reasonable: it follows the rules you wrote. It cannot show that the data is correct. A range check accepts 5 tickets because 5 is between 1 and 6, but it cannot know whether the user really meant 5 rather than 4. The program has checked the format and range, not the user's intention.
OCR GCSE Computer Science · Defensive Design