GoalUse selection to validate data before the program uses it, so that a bad value is turned away instead of causing a crash.
New words
validation · checking that data is reasonable and follows the rules before the program uses itrange check · a check that a number lies between the lowest and highest allowed valuespresence check · a check that something has been typedlength check · a check that a piece of text has an allowed number of characters
Explanation
Validation stops bad data at the door. A validation check is a selection: if the data passes, the program carries on, and if not, it prints a message and skips the risky line. The check you choose depends on the data. A range check compares a number with the lowest and highest allowed values. A presence check makes sure that something was typed, and a length check counts the characters with len(). A divisor can be checked to see that it is not 0, and a list position can be checked to see that it is at least 0 and less than len(list). Validation shows that data is reasonable, but not that it is true. A mark of 7 typed in place of the real mark of 8 still passes a range check from 0 to 10.
Check
Question it asks
Condition in Python
Range
is the number between low and high?
score >= 0 and score <= 10
Presence
did the user type anything?
len(name) > 0
Length
is the text short enough?
len(name) <= 12
List position
does that position exist?
n >= 0 and n < len(stops)
Divisor
is it safe to divide?
km > 0
Worked examples
Python
1km = int(input("Kilometres run? "))
2minutes = int(input("Minutes taken? "))
3if km > 0:
4print("Pace:", minutes / km, "minutes per km")
5else:
6print("Distance must be more than 0")
Output
Distance must be more than 0
Repairing the pace program from lesson 1. The if line checks the distance before the division. The user types 0 for the kilometres and 30 for the minutes, so the else branch runs and the program does not crash. With 5 and 30 the same program prints Pace: 6.0 minutes per km.
Python
1shelves = ["Maps", "Poems", "Cooking", "Sport"]
2choice = int(input("Shelf number (0 to 3)? "))
3if choice >= 0and choice < len(shelves):
4print("Shelf:", shelves[choice])
5else:
6print("No such shelf")
Output
No such shelf
Protecting a list. The list has four shelves at positions 0 to 3, so len(shelves) is 4. The condition accepts a choice from 0 up to 3 and turns away everything else. The user types 4, which is one place too far, so the program prints a message. With 2 typed it prints Shelf: Cooking.
Python
1name = input("Team name? ")
2iflen(name) == 0:
3print("Please type a name")
4eliflen(name) > 12:
5print("Name is too long")
6else:
7print("Welcome,", name)
Output
Name is too long
Two checks in a chain. A team name must be typed, and it may have at most 12 characters. For an empty name the program prints Please type a name. For Red Panthers, which has exactly 12 characters, it prints Welcome, Red Panthers. The user types Brilliant Badgers, which has 17 characters, so the length check turns it away.
Class activity
Guard the list (no computer). On a strip of paper write five items in a row and number the boxes 0 to 4. A partner calls out numbers, some of them too high and some negative. For each number you answer with the item or with No such position. Then both of you write the Python condition that would do the guarding, using len(). Finally change the list to seven items and decide what part of your condition changes and what part stays the same.
Practice
1
A ticket program accepts from 1 to 6 tickets. Write the condition that goes in place of the blank so that only whole numbers from 1 to 6 are accepted.
tickets >= 1 and tickets <= 6. The numbers 1 and 6 are accepted, while 0 and 7 make the else branch run.
2
The user types 0. What happens? Find the mistake in the check and write the repaired line.
Python
1people = int(input("People? "))
2if people >= 0:
3print("Each gets", 24 / people)
4else:
5print("Need at least 1 person")
The condition people >= 0 is true for 0, so the program divides by 0 and stops with ZeroDivisionError: division by zero. The check should be people > 0, which also rejects negative numbers.
3
A list is days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]. The user types a day number from 1 to 7. Write a program on paper that prints the day name for a valid number and No such day otherwise.
number = int(input("Day number (1 to 7)? ")) / if number >= 1 and number <= 7: / print(days[number - 1]) / else: / print("No such day"). The position is number − 1 because the list starts at 0. Test: 1 gives Mon, 7 gives Sun, 0 and 8 give No such day.
4
A learner says: ‘My program asks for a mark from 0 to 10. It accepted 9, but my real mark was 5, so validation failed.’ Is she right?
No. Validation checks that data is reasonable, and 9 is inside the range 0 to 10. It cannot know the real mark. The mistake was made by the person who typed, and only checking against another source could find it.