Corrected exercises: debugging and testing, errors, test plans and exceptions (ICS3U)
Exercises: debugging and testing, errors, test plans and exceptions (ICS3U)
Name: Class: Date:
Solutions
Suggested time: 2 h 30 · No calculator · 10 exercises https://www.letuteurscientifique.ca/en/exercices/ics3u-debugging-testing
These ten corrected exercises cover the eighth chapter of ICS3U, Introduction to Computer Science, Grade 11, University Preparation, in Ontario: identifying and correcting syntax, run-time and logic errors, interpreting the error messages of Python, the tracing technique and the extra print statements that output the state of the variables, validating a program on a full range of test cases with a test plan (scenarios, input data, expected outcomes, actual outcomes, pass or fail), and algorithms that detect, intercept and handle exceptions such as a division by zero or the square root of a negative number.
What the set covers, the traps it targets
The code is in Python 3, and the error messages are those that Python 3.13 printed for each program; older versions of Python 3 word some of them differently. Classifying, reading, tracing and testing work the same way in any language.
By the end, you can classify an error from the way it shows itself (exercise 1), read a traceback from its last line up (exercise 2), place a print that shows the variables and find the faulty line (exercise 3), fill in a test plan and conclude pass or fail (exercise 4), and place a guard or a try so that a division by zero or a word typed for a number is handled (exercise 5). Part B finds the amounts that get the wrong change from a vending machine (exercise 6), builds the test plan of a roller coaster's height check from its classes and boundaries (exercise 7), corrects five statements (exercise 8), fixes a restaurant bill program in the order Python reveals its three errors (exercise 9), and handles the square root of a negative number in a ladder app (exercise 10).
The thread of the set: an error is found by the way it shows itself. A syntax error stops the program before its first line runs, a run-time error stops it at the line where Python detects it, which is not always the line that caused it, and a logic error stops nothing: it is found by comparing the actual outcome with an expected outcome computed by hand. Five traps are named in the solutions: (1) a logic error stops nothing, and the program runs to a plausible wrong result, exercises 1, 3, 4, 6, 8 and 9; (2) the line named by the message is where the error was detected, while the faulty value may come from an earlier line, exercises 1, 2, 8 and 9; (3) a test that passes does not prove the program correct, exercises 4, 6 and 8; (4) a test plan without boundary values or invalid entries, exercises 4, 7 and 10; (5) the divisor tested after the division, and a try that wraps everything and hides the real error, exercises 5 and 10. That a syntax error anywhere stops the whole file comes back in exercises 1, 8 and 9.
No calculator is needed: every trace, every expected outcome and every count is worked out by hand, as on a unit test. Automated unit tests, preconditions and postconditions belong to the Grade 12 course, ICS4U; here a program is tested by hand, with a test plan.
The homework without solutions, one exercise per page, and the solutions on their own: it comes with your free space. An email is enough, no password, and you come back here.
•Syntax error: a rule of the language is broken; Python refuses the file and no line runs.
•Run-time error: the program stops at the line Python cannot carry out and prints a traceback.
•Logic error: no message; the result is wrong, and a comparison with an expected outcome computed by hand shows it.
•A traceback is read from the bottom: the last line gives the exception and its message, the last File line gives where Python stopped.
•The line named by the message is where the error was detected; the faulty value may come from an earlier line.
•Test plan: scenario, input, expected outcome from the specification, actual outcome, pass or fail.
•A plan holds normal values, both sides of every boundary, and entries that are not valid.
•A guard comes BEFORE the risky line; a try holds only the line that can fail, with except ValueError: rather than a bare except:.
Part A: the basics (/50)
Exercise 1: Syntax, run-time or logic: one program, five broken versions
11 answers to check
An error is classified by when and how it shows itself. A syntax error breaks a rule of the language: Python reads the whole file before it runs any line, so it refuses the program and no line runs. A run-time error happens while the program runs: the lines before it run, then Python stops at the line it cannot carry out and prints a message. A logic error breaks no rule and stops nothing: the program runs to the end and gives a wrong result.
The program below converts the laps a student runs on a 400 m track into kilometres. It is correct: for 12 laps, it prints Distance: 4.8 km. Each part changes ONE line of it, and the user types 12 each time.
track.py
laps = int(input("Laps: ")) # line 1
length = 400 # line 2
distance = laps * length / 1000 # line 3
print("Distance:", distance, "km") # line 4
a) Line 4 becomes print("Distance:" distance, "km"), without the comma after "Distance:". Which kind of error is it? Does the prompt Laps: appear before the program stops?
b) Line 3 becomes distance = laps * lenght / 1000. Which kind of error is it? Which line does the message name?
c) Line 3 becomes distance = laps * length / 100. Which kind of error is it? What number does the program print after Distance:?
d) Line 1 becomes laps = input("Laps: "). Which kind of error is it? Which line does the message name? On which line did laps receive the value that causes it?
e) Line 4 is moved four spaces to the right, the other lines unchanged. Which kind of error is it? Does the prompt Laps: appear?
Show the solution
Answers
a)Syntax error; Laps: does not appear
b)Run-time error, a NameError on line 3
c)Logic error: it prints Distance: 48.0 km instead of 4.8 km
d)Run-time error, a TypeError on line 3; laps received a string on line 1
e)Syntax error, an IndentationError; Laps: does not appear
Ask two questions: does the program start, and does it stop with a message? The messages quoted are those of Python 3.13; the table below sums up the three kinds.
a)
Two values side by side with no comma between them break a rule of Python. Python reads the whole file before running it, refuses it, and prints line 4 with SyntaxError: invalid syntax. Perhaps you forgot a comma?
Nothing runs, not even line 1: the prompt Laps: never appears, although the error is on the last line.
Pitfall: expecting lines 1 to 3 to run first. A syntax error anywhere in the file stops the whole file.
b)
lenght is a valid name, so the file follows every rule and starts. Line 1 shows Laps: and reads 12, line 2 runs, then line 3 asks for lenght, a name that was never assigned.
Python stops with NameError: name 'lenght' is not defined. Did you mean: 'length'? The message names line 3: a run-time error, after lines 1 and 2 have run.
c)
Every line runs and no message appears: 12 × 400 / 100 = 48.0, and the program prints Distance: 48.0 km.
4800 m is 4.8 km: dividing by 100 gives hundreds of metres, not kilometres.
Pitfall: a logic error gives no message. The value computed by hand, 4.8, shows that 48.0 is wrong.
d)
input() returns a string: laps holds '12'. On line 3, '12' * 400 repeats the string 400 times, which is allowed, then the division of a string by 1000 is not: TypeError: unsupported operand type(s) for /: 'str' and 'int', on line 3.
The faulty value was created on line 1, and the fix goes there: laps = int(input("Laps: ")).
Pitfall: the line named by the message is the line where Python noticed the problem, not always the line that caused it.
e)
A line indented when no block calls for it breaks a rule: IndentationError: unexpected indent, on line 4. IndentationError is a kind of SyntaxError, and, as in a), nothing runs: Laps: never appears.
Points are earned before the solution; after it, you can keep practising.
For you:
Tick the exercises you have done or want to review: a free account, no password, keeps your ticks and your right answers from one visit to the next, tells you which chapter to tackle next and lets you ask for the exercise you are missing. Create your space, an email is enough.
Exercise 2: Reading a traceback: from the last line up
9 answers to check
When a run-time error stops a program, Python prints a traceback: the chain of calls that led to the error, most recent call last. Its last line gives the type of the exception and a message. Each File line above it names a file, a line number and the function that line is in, followed by the line of code; since Python 3.11, marks ~ and ^ underline the part that failed. Python writes the whole folder path in front of the file name; only the file name is kept here.
A reading log computes a reading speed in pages per hour. A student runs it, types 45 pages and 30 minutes, and the Shell shows what is below the program.
reading.py, then the Shell
def pages_per_hour(pages, minutes): # line 1
rate = pages / minutes * 60 # line 2
return round(rate, 1) # line 3
pages = int(input("Pages read: ")) # line 4
minutes = input("Minutes: ") # line 5
speed = pages_per_hour(pages, minutes) # line 6
print("Speed:", speed, "pages per hour") # line 7
Pages read: 45
Minutes: 30
Traceback (most recent call last):
File "reading.py", line 6, in <module>
speed = pages_per_hour(pages, minutes)
File "reading.py", line 2, in pages_per_hour
rate = pages / minutes * 60
~~~~~~^~~~~~~~~
TypeError: unsupported operand type(s) for /: 'int' and 'str'
a) What is the type of the exception?
b) On which line did Python stop? In which part of the program is that line?
c) Why does line 6 appear in the traceback too?
d) Which line must change so that the program prints Speed: 90.0 pages per hour? What does it become?
e) After that change, the student types 45, then thirty. Which exception stops the program now, on which line? How many File lines does the new traceback have?
Show the solution
Answers
a)TypeError
b)Line 2, in the function pages_per_hour
c)Line 6 called pages_per_hour, and the error happened during that call
d)Line 5: minutes = int(input("Minutes: "))
e)A ValueError on line 5; 1 File line
Read a traceback from the bottom: the last line says what went wrong, the last File line says where, and the File lines above it say how the program got there.
a)
The last line is TypeError: unsupported operand type(s) for /: 'int' and 'str'. A TypeError means an operation received a value of the wrong type: here / got a whole number on its left, pages = 45, and a string on its right, minutes = '30'.
b)
The last File line is File "reading.py", line 2, in pages_per_hour: Python stopped on line 2, inside the function, while it computed pages / minutes * 60. The ~ and ^ marks point at the division.
c)
The first File line ends with in <module>, the name Python gives to the main program: line 6 called pages_per_hour(pages, minutes). The second File line is the line that was running inside that call.
Line 6 is correct; it is listed because it led to line 2.
Pitfall: reading the traceback from the top and fixing the first line it names.
d)
The string came from line 5: input() returns a string, and minutes = input("Minutes: ") keeps '30'. Line 5 becomes minutes = int(input("Minutes: ")).
Then 45 / 30 × 60 = 90.0, round(90.0, 1) = 90.0, and the program prints Speed: 90.0 pages per hour.
Pitfall: changing line 2 because the message names it. The value was created wrong on line 5: convert it where it is read.
e)
int('thirty') is impossible: the program stops on line 5, before the function is called, with ValueError: invalid literal for int() with base 10: 'thirty'.
The error happens in the main program, so the traceback has 1 File line. A ValueError means the type was right, a string for int(), but not its value. The second Shell is below.
The Shell, second run
Pages read: 45
Minutes: thirty
Traceback (most recent call last):
File "reading.py", line 5, in <module>
minutes = int(input("Minutes: "))
ValueError: invalid literal for int() with base 10: 'thirty'
Points are earned before the solution; after it, you can keep practising.
For you:
Exercise 3: Print the state of the variables: a step counter that counts too many days
9 answers to check
A trace on paper, or extra print statements that display the variables at each pass, shows where a program starts to go wrong: the first value that differs from the value computed by hand points to the faulty line.
A fitness tracker should display the number of days of a week with at least 10,000 steps, then the average number of steps per day, rounded to the unit. The test case is the week in the table, typed day by day.
Day
1
2
3
4
5
6
7
Steps
8200
11500
6400
10000
9100
12300
7000
steps.py
goal_days = 0 # line 1
total = 0 # line 2
for day in range(1, 8): # line 3
steps = int(input("Steps: ")) # line 4
total = total + steps # line 5
if total >= 10000: # line 6
goal_days = goal_days + 1 # line 7
print(goal_days, "days at the goal") # line 8
print("Average:", round(total / 7), "steps") # line 9
a) Work out the expected outcome from the table, by hand: how many days reach the goal? What is the average, rounded to the unit?
b) The program prints 6 days at the goal, then Average: 9214 steps. Does the test pass or fail?
c) A student adds print("DEBUG", day, steps, total) as a new line between lines 5 and 6, indented like line 5. How many DEBUG lines does a run print? What total does the DEBUG line of day 3 show?
d) On which line is the error? What does that line become?
e) After the fix, a classmate writes > in place of >= on the corrected line. How many days at the goal does the program print now? Which value of the table shows the change?
Show the solution
Answers
a)3 days; average 9214 steps
b)Fail
c)7 DEBUG lines; total 26100 on day 3
d)Line 6, which becomes if steps >= 10000:
e)2 days; the 10000 of day 4 shows it
A test compares an expected outcome, computed from the specification before the run, with the actual outcome. When they differ, the debugging output tells where the values leave the hand computation. The table below puts what the goal asks next to what line 6 tests.
a)
Days with at least 10,000 steps: day 2 (11500), day 4 (10000) and day 6 (12300), so 3 days. « At least » includes 10,000.
Expected 3 days, actual 6: the test fails, although the average is right and no message appears.
Pitfall: a logic error stops nothing. Without the expected 3, the output 6 days at the goal looks plausible.
c)
The new line is in the body of the loop: one DEBUG line per pass, 7 lines.
Day 1: DEBUG 1 8200 8200. Day 2: DEBUG 2 11500 19700. Day 3: DEBUG 3 6400 26100.
On day 3, the steps are 6400, under the goal, and total is 26100: line 6 compares total, which passed 10000 on day 2 and stays above it, so every day from day 2 counts.
d)
The goal is about the steps of one day, not the running total: line 6 becomes if steps >= 10000:.
Run again with the same test: 3 days at the goal, Average: 9214 steps. The test passes. The DEBUG line is then removed.
e)
With if steps > 10000:, day 4 (10000 steps) no longer counts: 2 days.
Only the value 10000, which lies on the boundary, shows the difference: a test without a value on the boundary would pass with either sign.
Points are earned before the solution; after it, you can keep practising.
For you:
Exercise 4: A test plan: expected outcome, actual outcome, pass or fail
9 answers to check
A test plan lists, before the program is run, the scenarios to try, the input of each, and the expected outcome computed from the specification. The program is then run on each input, the actual outcome is recorded, and each test is concluded: pass when the two agree, fail otherwise.
The specification of a school library: a book returned late costs 0.25 dollars per day late, and the fee never goes above 10.00 dollars. A book returned on time or early, 0 days late or a negative number of days, costs nothing. The function late_fee receives the number of days late, a whole number, and returns the fee in dollars. The plan has seven tests.
Test
Scenario
days
Expected (dollars)
Actual
Pass or fail
1
Normal
12
2
Returned on time
0
3
Returned early
-3
4
One day late
1
5
The fee reaches the cap
40
6
Just past the cap
41
7
Far past the cap
60
Python
def late_fee(days): # line 1
if days <= 0: # line 2
return 0.0 # line 3
if days > 50: # line 4
return 10.0 # line 5
return days * 0.25 # line 6
a) Compute the expected outcome of tests 1, 5 and 6 from the specification.
b) Trace late_fee for tests 5 and 6: what does it return?
c) Fill in the whole plan. How many of the seven tests fail?
d) For which whole numbers of days does late_fee return a wrong fee? Give them as an interval of whole numbers.
e) A first plan had only tests 1, 2 and 7. How many of its tests fail? Which line 4 makes the function correct for every whole number?
Show the solution
Answers
a)3.00, 10.00 and 10.00 dollars
b)10.0 for 40 days; 10.25 for 41 days
c)1 test fails: test 6
d)From 41 to 50 days, [41, 50]
e)0 fails; if days > 40:
The expected column comes from the specification, never from the code: otherwise the plan only checks that the program does what it does. The filled plan is below.
a)
Test 1: 12 × 0.25 = 3.00 dollars. Test 5: 40 × 0.25 = 10.00 dollars, the cap itself. Test 6: 41 × 0.25 = 10.25, above the cap, so 10.00 dollars.
b)
Test 5: 40 <= 0 is False, 40 > 50 is False, so line 6 returns 40 × 0.25 = 10.0.
Test 6: 41 > 50 is False as well, so line 6 returns 41 × 0.25 = 10.25: 0.25 dollars above the cap.
c)
Test 1: 3.0, pass. Tests 2 and 3: line 2 returns 0.0, pass. Test 4: 0.25, pass. Test 5: 10.0, pass. Test 6: 10.25 against 10.00, fail. Test 7: 60 > 50, line 5 returns 10.0, pass.
1 test out of 7 fails.
Pitfall: six passes do not make the function correct. A test that passes shows that the function is right for that input only.
d)
Line 4 lets every value up to 50 reach line 6: from 41 days on, days × 0.25 is above 10.00. From 51 days on, line 5 returns 10.0.
Wrong for 41, 42, ..., 50: ten values, from 10.25 to 12.50 dollars.
e)
Tests 1, 2 and 7 all pass: that plan says nothing about 41 to 50, since it has no value near the cap.
Pitfall: a plan without boundary values. The cap is reached at 40 days: test 40 and 41, the values on each side.
Line 4 becomes if days > 40:, which returns 10.0 from 41 days on; at 40 days, line 6 gives 10.0 as well.
Points are earned before the solution; after it, you can keep practising.
For you:
Exercise 5: Exceptions: a guard before the division, a try that catches only what it should
10 answers to check
An exception is an error detected while the program runs: a division by zero raises ZeroDivisionError, and int() given text that is not a whole number raises ValueError. A program can detect the problem before it happens, with a guard, an if placed BEFORE the risky line. It can also intercept it with try and except: when a line of the try block raises the exception named after except, Python jumps to the except block instead of stopping.
A class orders pizza for a party: each pizza is cut into 8 slices, shared equally, and the slices that cannot be shared are left over.
party.py
pizzas = int(input("Pizzas: ")) # line 1
people = int(input("People: ")) # line 2
slices = pizzas * 8 # line 3
each = slices // people # line 4
left = slices % people # line 5
if people == 0: # line 6
print("No one to share with") # line 7
else: # line 8
print(each, "slices each,", left, "left over") # line 9
a) What does the program print for 5 pizzas and 12 people?
b) The user types 5, then 0. Does line 7 print its message? Which exception stops the program, on which line?
c) The user types 5, then twelve in letters. Which exception stops the program, on which line?
d) Which change makes the guard of line 6 work?
e) A student writes another version: try:, then the two input lines, slices = pizzas * 8, each = slices // people and print(each, "slices each") in the try block, then except: and print("Please type whole numbers"). What does it print for 5 and 0? Which except line keeps the message for letters, without hiding the division by zero?
Show the solution
Answers
a)3 slices each, 4 left over
b)No; a ZeroDivisionError on line 4
c)A ValueError on line 2
d)Move lines 4 and 5 into the else block, before line 9
e)Please type whole numbers, a wrong message; except ValueError:
A guard must come before the line it protects, and a try must catch only the exception it is meant for. The corrected program is below.
a)
5 × 8 = 40 slices; 40 // 12 = 3 and 40 % 12 = 4, since 3 × 12 = 36. It prints 3 slices each, 4 left over.
b)
Line 4 divides by people before line 6 tests it: 40 // 0 stops the program with ZeroDivisionError: integer division or modulo by zero, on line 4. Line 7 never runs.
Pitfall: testing the divisor after the division. The test exists, but it comes too late.
c)
int('twelve') is impossible: ValueError: invalid literal for int() with base 10: 'twelve', on line 2. The prompt People: has appeared, and nothing after it runs.
d)
The divisions must run only when people is not 0: lines 4 and 5 move into the else block, just before the print of line 9. Then 5 and 0 print No one to share with.
Writing if people = 0: is a syntax error; moving line 6 to the top tests people before it exists, a NameError.
e)
The bare except: catches every exception. With 5 and 0, the division raises ZeroDivisionError, and the program prints Please type whole numbers: the user did type whole numbers, and the message hides the real problem.
Pitfall: a try that wraps everything with except: alone. With except ValueError:, the message stays for letters, and 0 people still stops the program with its own ZeroDivisionError, which a guard then handles.
The corrected program keeps only the two input lines in the try block, sets a flag ok to False when they fail, and guards the division with people > 0, which also refuses a negative number of people.
Python
ok = True
try:
pizzas = int(input("Pizzas: "))
people = int(input("People: "))
except ValueError:
print("Please type whole numbers")
ok = False
if ok:
if people > 0:
slices = pizzas * 8
print(slices // people, "slices each,", slices % people, "left over")
else:
print("No one to share with")
Points are earned before the solution; after it, you can keep practising.
For you:
Part B: problems and reasoning (/50)
Exercise 6: Problem: the change of a vending machine, and a test that passes for the wrong reason
13 answers to check
The vending machine of a school cafeteria sells items priced in multiples of 5 cents and gives change in quarters (25 cents), dimes (10 cents) and nickels (5 cents): as many quarters as possible, then as many dimes as possible, then nickels. The program receives the change due in cents, a multiple of 5 from 5 to 95.
change.py
cents = int(input("Change due (cents): ")) # line 1
quarters = cents // 25 # line 2
left = cents % 25 # line 3
dimes = left // 10 # line 4
left = cents % 10 # line 5
nickels = left // 5 # line 6
print("Quarters:", quarters, "Dimes:", dimes, "Nickels:", nickels) # line 7
a) What does the program print for 65 cents? Does this test pass?
b) What does it print for 40 cents? Does this test pass?
c) To check any amount at a glance, a student adds print(25 * quarters + 10 * dimes + 5 * nickels) after line 7: the value of the coins given. What does that line print for 40 cents?
d) Of the 19 possible amounts, 5, 10, ..., 95, how many get the wrong change? What is the smallest of them?
e) Which line is wrong? What does it become?
Show the solution
Answers
a)Quarters: 2 Dimes: 1 Nickels: 1; pass
b)Quarters: 1 Dimes: 1 Nickels: 0; fail, 35 cents given
c)35
d)10 amounts; the smallest is 25 cents
e)Line 5, which becomes left = left % 10
Trace the variables line by line, then compare with change counted by hand. The extra line of c) is debugging output: it shows the state of the program, the value given back, next to the value due. The figure below shows which amounts fail.
It prints Quarters: 2 Dimes: 1 Nickels: 1: 50 + 10 + 5 = 65 cents. The test passes.
b)
40 // 25 = 1 quarter, left = 15, dimes = 1. Line 5: left = 40 % 10 = 0, nickels = 0.
It prints Quarters: 1 Dimes: 1 Nickels: 0: 35 cents for 40 due. The test fails: by hand, 40 cents is 1 quarter, 1 dime and 1 nickel.
c)
25 × 1 + 10 × 1 + 5 × 0 = 35: the line prints 35, and 35 is not 40. Such a line turns every run into a test that the program checks for you.
d)
Line 5 takes the remainder of cents, not of what is left after the quarters. When the number of quarters is even, 25 × quarters ends in 0, so cents % 10 equals left % 10 and the result is right.
When it is odd, 25 × quarters ends in 5, and the nickel is given when it should not be, or missing when it should be there.
Odd numbers of quarters: 1 for 25 to 45 cents, 3 for 75 to 95 cents. 10 amounts out of 19 fail, the smallest being 25 cents: 1 quarter and 1 nickel, 30 cents.
Pitfall: the test of a) passes. A test that passes proves that the program is right for that input, and 65 has 2 quarters, an even number.
e)
Line 5 must keep the remainder of left: left = left % 10. Run again with the check line of c): it prints the amount due for all 19 amounts.
Then remove the check line, which is not part of the specification.
Points are earned before the solution; after it, you can keep practising.
For you:
Exercise 7: Problem: classes and boundaries, the test plan of a roller coaster's height check
8 answers to check
A test plan is built from the specification, before the code is read. The inputs are split into classes, sets of inputs that the program must treat the same way, and every boundary between two classes is tested on both sides, since a < written for <= is wrong on the boundary value only.
The specification of the height check of a roller coaster: riders from 122 cm to 196 cm tall, both included, may board. The operator types the height in whole centimetres. A height under 50 cm or over 250 cm is a typing error. The program prints one of five messages: Welcome aboard, Too short, Too tall, Invalid height, or Please type a whole number when the entry is not a whole number. The figure draws the specification, not to scale.
ride.py
height = int(input("Height (cm): ")) # line 1
if height < 50 or height > 250: # line 2
print("Invalid height") # line 3
elif height < 122: # line 4
print("Too short") # line 5
elif height < 196: # line 6
print("Welcome aboard") # line 7
else: # line 8
print("Too tall") # line 9
a) Into how many classes does the specification split the inputs, counting the entries that are not whole numbers as one class?
b) Each boundary between two numeric classes is tested on both sides. How many boundary values is that? What is the largest of them?
c) A plan keeps the boundary values and one entry that is not a whole number. How many tests is that? Does it test every class?
d) A first plan has one typical value per class: 30, 100, 150, 220, 300 and tall. How many of its six tests fail with the program above?
e) How many tests of the plan of c) fail with the program above? Which height is wrongly refused?
Show the solution
Answers
a)6 classes
b)8 values; the largest is 251
c)9 tests; yes, every class
d)1 test fails: tall
e)2 tests fail, 196 and tall; 196 cm is wrongly refused
Classes first, then boundaries, then the expected outcome of each test, all from the specification. The classes are drawn below.
a)
Invalid, 49 or less; Too short, 50 to 121; Welcome aboard, 122 to 196; Too tall, 197 to 250; Invalid, 251 or more; and the entries that are not whole numbers: 6 classes.
The two Invalid classes print the same message, but they sit on two sides of the line, with a boundary each.
b)
Four boundaries: 49 | 50, 121 | 122, 196 | 197, 250 | 251, so 8 values, the largest being 251.
c)
8 boundary values + 1 entry such as tall = 9 tests. Every numeric class holds at least one boundary value: 49 and 251 for the Invalid classes, 50 and 121, 122 and 196, 197 and 250. With tall, all 6 classes are tested.
d)
30 Invalid height, 100 Too short, 150 Welcome aboard, 220 Too tall, 300 Invalid height: 5 passes.
tall: line 1 stops with ValueError: invalid literal for int() with base 10: 'tall', where the specification asks for Please type a whole number. 1 fail.
Pitfall: a plan of typical values only. It finds the crash but not the bug of e).
e)
196: 196 < 196 is False on line 6, so the else of line 8 prints Too tall, where the specification says Welcome aboard. tall fails as in d). The 7 other boundary values pass: 2 fails.
Fixes: line 6 becomes elif height <= 196:, and int(input()) goes in a try block with except ValueError:. The corrected program is below.
Python
ok = True
try:
height = int(input("Height (cm): "))
except ValueError:
print("Please type a whole number")
ok = False
if ok:
if height < 50 or height > 250:
print("Invalid height")
elif height < 122:
print("Too short")
elif height <= 196:
print("Welcome aboard")
else:
print("Too tall")
Points are earned before the solution; after it, you can keep practising.
For you:
Exercise 8: Five statements to correct
11 answers to check
Each statement below was written by a student. Say whether it is true or false, answer the question that checks it, and correct the false ones.
a) « My program printed no error message, so it is correct. » A program meant to print the average of a = 70 and b = 90 runs average = a + b / 2, then print(average). What does it print?
b) « The line to fix is always the line that the message names. » Line 1 is age = input("Age: ") and line 2 is print("Next year:", age + 1); the user types 16. Which line does the message name? On which line did age receive a string?
c) « All the tests of my plan pass, so the program has no bug. » A program meant to count the multiples of 3 from 1 to n runs count = 0, then for k in range(1, n): if k % 3 == 0: count = count + 1. Its tests n = 10 and n = 20 pass. For how many values of n from 1 to 30 is the count wrong?
d) « A syntax error on the last line lets the lines above it run first. » Lines 1 to 4 each print a word, and line 5 is print("done" with no closing parenthesis. How many lines does the program display?
e) « Since the user can type anything, a test plan needs at least one entry that is not valid. » Line 1 of a program is laps = int(input("Laps: ")), and the user types twelve. On which line does the program stop?
Show the solution
Answers
a)False: it prints 115.0, not 80
b)False: the message names line 2, the string came from line 1
c)False: wrong for 10 values of n
d)False: 0 lines
e)True: it stops on line 1
a)
False. / is computed before +: average = 70 + 45.0 = 115.0, and the program prints 115.0 with no message. The average is (70 + 90) / 2 = 80.0.
Correct statement: « No error message rules out syntax and run-time errors on this input; a test with an expected outcome computed by hand checks the result. »
b)
False. Line 2 stops with TypeError: can only concatenate str (not "int") to str: the message names line 2. The string was created on line 1, since input() returns a string.
Correct statement: « The message names the line where Python detected the error; the cause can be on an earlier line. »
c)
False. range(1, n) stops before n, so n itself is never tested. The count is wrong for the n that are multiples of 3: 3, 6, ..., 30, that is 10 values. 10 and 20 are not multiples of 3, so both tests pass.
Correct statement: « Tests that pass show the program is right for those inputs; the plan must hold the cases where it could fail, here an n that is a multiple of 3. »
d)
False. Python reads the whole file first and refuses it: SyntaxError: '(' was never closed, on line 5. Nothing is displayed.
Correct statement: « A syntax error anywhere stops the whole file before its first line runs. »
e)
True. int('twelve') raises ValueError: invalid literal for int() with base 10: 'twelve' on line 1. A plan with valid entries only never shows this crash.
Points are earned before the solution; after it, you can keep practising.
For you:
Exercise 9: Problem: a restaurant bill with three errors, fixed in the order Python shows them
12 answers to check
Friends split a restaurant bill. The program reads the subtotal in dollars and the number of people, adds 13 % tax and a 15 % tip, both computed on the subtotal, and prints each person's share, rounded to the cent. The file below holds three errors. The student runs it, fixes what the run shows, and runs it again, until it works. The test case: a subtotal of 70 dollars for 4 people.
bill.py
subtotal = float(input("Subtotal (dollars): ")) # line 1
people = input("People: ") # line 2
tax = subtotal * 1.13 # line 3
tip = subtotal * 0.15 # line 4
total = subtotal + tax + tip # line 5
share = total / people # line 6
print("Each pays", round(share, 2), "dollars" # line 7
a) Run 1. Which kind of error does the Shell show? Does the prompt Subtotal (dollars): appear? Which line does the message name?
b) Run 2, after that line is fixed, with 70 and 4. Which exception stops the program, on which line? On which line did the faulty value get created?
c) Run 3, after that fix. Compute the expected share by hand. What does the program print as the share? Does the test pass?
d) The student adds print("DEBUG", tax, tip, total) after line 5. What does it show for tax? Which line holds the last error?
e) After the three fixes, the plan adds a test with 0 people. What happens?
Show the solution
Answers
a)A syntax error; the prompt does not appear; line 7
b)A TypeError on line 6; the string was created on line 2
c)Expected 22.40 dollars; it prints 39.9; fail
d)tax = 79.1; line 3
e)A ZeroDivisionError on line 6
Python shows the errors by kind, not in the order of the lines: first the syntax errors, since it refuses the file, then the run-time errors, one per run, and the logic errors last, through a test. The four runs are below.
a)
Line 7 misses its closing parenthesis. Python refuses the file: SyntaxError: '(' was never closed, on line 7, and nothing runs, so the prompt never appears.
The run-time error of line 6 is earlier in the file, yet it cannot show before the file is accepted.
b)
Line 7 ends with ). The prompts appear, 70 and 4 are typed, and line 6 stops: TypeError: unsupported operand type(s) for /: 'float' and 'str'.
people holds '4', a string, since line 2 has no int(): line 2 becomes people = int(input("People: ")).
The program prints Each pays 39.9 dollars: no message, and the test fails.
Pitfall: a program that runs is not a program that works. Without the expected 22.40, 39.9 looks like a share.
d)
The DEBUG line shows DEBUG 79.1 10.5 159.6: tip is 10.5 as computed by hand, tax is 79.1 instead of 9.1. The first wrong value is tax, so the error is on line 3.
70 × 1.13 = 79.1 is the subtotal WITH its tax, not the tax: line 3 becomes tax = subtotal * 0.13, and run 4 prints Each pays 22.4 dollars, the expected 22.40. The test passes; remove the DEBUG line.
e)
total / 0 stops the program on line 6 with ZeroDivisionError: float division by zero. A guard if people > 0: before line 6 handles it.
Points are earned before the solution; after it, you can keep practising.
For you:
Exercise 10: Problem: the square root of a negative number, in a ladder app
9 answers to check
A hardware store's app tells how high a ladder reaches. A ladder of length L, in metres, leans against a vertical wall, its foot on level ground at a distance d from the wall: by the Pythagorean theorem it reaches the height h = √(L² − d²).
The specification: lengths are typed in metres; an entry that is not a number prints Please type a number; a foot distance that is not strictly between 0 and L prints The foot must be between 0 m and the ladder length; otherwise the program prints the height, rounded to the centimetre. The table is the test plan.
Test
Scenario
L (m)
d (m)
1
Normal
6
1.5
2
Foot at the wall
6
0
3
Foot as far as the length
6
6
4
Foot farther than the length
3
4
5
Negative distance
6
-1.5
6
Not a number
six
ladder.py
import math # line 1
length = float(input("Ladder length (m): ")) # line 2
foot = float(input("Foot distance (m): ")) # line 3
height = math.sqrt(length ** 2 - foot ** 2) # line 4
print("It reaches", round(height, 2), "m") # line 5
a) What is the expected outcome of test 1?
b) Run test 4 on the program above. Which exception stops it, on which line? What is the message after the colon?
c) How many of the six tests fail with the program above?
d) A student puts lines 2 to 5 in a try block, followed by except ValueError: and print("Please type a number"). What does it print for test 4? How many of the six tests fail now?
e) Write a program that passes the whole plan. What does it print for test 5? How many tests fail with it?
Show the solution
Answers
a)It reaches 5.81 m
b)A ValueError on line 4: math domain error
c)5 tests fail; only test 1 passes
d)Please type a number, a wrong message; 4 tests fail
e)The foot message; 0 tests fail
The plan holds a normal case, the boundaries 0 and L, values past them, and an entry that is not a number. The plan run on the first program is below, and a program that passes it after it.
a)
h = √(6² − 1.5²) = √(36 − 2.25) = √33.75 = 5.809..., rounded to the centimetre: It reaches 5.81 m.
b)
3² − 4² = 9 − 16 = −7, and math.sqrt has no value for a negative number: ValueError: math domain error, on line 4. A ladder 3 m long cannot have its foot 4 m from the wall.
c)
Test 1 passes. Test 2 prints It reaches 6.0 m and test 3 It reaches 0.0 m, where the foot message is expected. Test 4 stops on line 4. Test 5 prints It reaches 5.81 m, since (−1.5)² = 2.25: a nonsense distance is accepted. Test 6 stops on line 2 with ValueError: could not convert string to float: 'six'.
5 tests fail, and none of them prints the message the specification asks for.
Pitfall: a plan with the normal case only would have passed this program.
d)
Test 4: math.sqrt raises a ValueError inside the try, and the except prints Please type a number, although 3 and 4 are numbers. Test 6 now passes; tests 2, 3, 4 and 5 fail: 4 fails.
Pitfall: a try that wraps everything. Two lines raise ValueError here, float() and math.sqrt, and one except cannot tell them apart.
e)
Keep only the two conversions in the try block, set ok to False when they fail, then guard the square root with foot > 0 and foot < length: past the guard, L² − d² is positive and math.sqrt cannot fail.
Test 5: −1.5 > 0 is False, so it prints The foot must be between 0 m and the ladder length. Tests 1 to 6 all give their expected outcome: 0 fails.
Python
import math
ok = True
try:
length = float(input("Ladder length (m): "))
foot = float(input("Foot distance (m): "))
except ValueError:
print("Please type a number")
ok = False
if ok:
if foot > 0 and foot < length:
height = math.sqrt(length ** 2 - foot ** 2)
print("It reaches", round(height, 2), "m")
else:
print("The foot must be between 0 m and the ladder length")
Points are earned before the solution; after it, you can keep practising.
Something missing from this set?A type of exercise your teacher gives, a problem you are stuck on, a mistake you spotted: tell me, I read every request.
Sending goes through your free space: that is how I can answer you and tell you when the exercise is added. An email is enough, no password. Create your space.
Rather not create an account? Write to me directly.
I tutor Grade 11 computer science in English or in French, online. Get in touch for a first session: reading errors and writing test plans come back in every assignment of the course.