Defensive Design
A validation check tests input against a rule before the program uses it. If it passes, the input is accepted; if it fails, the program can reject it and say what was expected. Choose a check that matches the data.
| Check | What it tests | Example rule |
|---|---|---|
| Range | the value is between lower and upper limits | club trip places must be 1 to 6 |
| Type | the data is the expected type before use or conversion | places must be a whole number, so 2.5 fails |
| Length | the number of characters is within limits | a locker code must be 3 to 5 characters |
| Presence | something has been entered | a saved game title cannot be empty |
| Format | the characters follow a required pattern | a gym membership code is three letters then two digits, such as ABC12 |
| Look-up (table) | the value is one of a set of allowed values | a canteen meal must be hot, cold or salad |
A range check must test both limits. Testing only the bottom limit lets 500 places through, and testing only the top limit lets -4 through. Join the two tests with or so anything outside either limit is rejected: if count < 1 or count > 6. Use the comparison that matches each boundary so an allowed limit is accepted.
input() always gives text, so a number of places of 4 arrives as "4". int() converts digits but stops with an error on other text. Check the expected type first, then convert only once it passes.
One rule is often not enough: a number of places may need presence, type and range checks; a membership code may need length plus format. Empty input also fails a length check because its length is 0. Rules must fit the data and purpose: a range check suits a number of places, not a name, and limits should reflect what the program allows.
places = input("How many places? ")
valid_number = len(places) > 0 # presence check using length
for ch in places:
if ch < "0" or ch > "9":
valid_number = False # type check: every character a digit
if not valid_number:
print("Enter a whole number of places")
else:
count = int(places) # safe to convert now
if count < 1 or count > 6:
print("Choose between 1 and 6 places")
else:
print(count, "places booked")Output when the user types 4.5:
How many places? 4.5
Enter a whole number of places OCR GCSE Computer Science · Defensive Design