Menu

Defensive Design

Validation checks

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.

CheckWhat it testsExample rule
Rangethe value is between lower and upper limitsclub trip places must be 1 to 6
Typethe data is the expected type before use or conversionplaces must be a whole number, so 2.5 fails
Lengththe number of characters is within limitsa locker code must be 3 to 5 characters
Presencesomething has been entereda saved game title cannot be empty
Formatthe characters follow a required patterna gym membership code is three letters then two digits, such as ABC12
Look-up (table)the value is one of a set of allowed valuesa canteen meal must be hot, cold or salad

Check both ends of a range

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.

Type checks come before conversion

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.

Combining checks

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

Practise this