…
…
Python Programming Fundamentals · Lesson 18 / 40 · Errors, debugging, and tests
PreviewIn this lesson you will
print to trace the program and find the first line where a value departs from the expected oneYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Corner Café's end-of-day report shows a revenue of $8.50 even though 3 lattes were sold today, while the register holds $12.75. The same report also writes the latte count as 1, and there is not a single red line on the screen, not a single error message. Ada asks you to find which line of the report is lying; in this lesson you will trace the culprit and fix it.
At the end of the lesson you will repair the report. For 3 sales at $4.25 and the orders "LCLTL" (L latte, C cookie, T tea), the repaired report will print:
OutputRevenue: 12.75
Lattes: 3In this lesson you will be able to:
print and find the first line where a value departs from what you expected.In the previous lesson you read errors where Python stopped you with a red message: NameError, TypeError, IndentationError. Those errors are annoying but honest; they tell you the line number and the type of the problem. The errors you will meet in this lesson are silent. The program runs to the end and prints a number, but the number is wrong. From Python's point of view there is no problem: it did what you wrote. This gap between what you wanted and what you wrote is called a logic error. Logic errors are the hardest errors to find, because nobody tells you where to look.
The report's revenue calculation is written like this:
Example 1 (case): The revenue calculation
def revenue(sales_count, price): total = 0.0 for turn in range(1, sales_count): total += price return total print(revenue(3, 4.25))
Output8.5The code looks fine: the total starts from zero, the price is added on every sale, the result is returned. There is no typing mistake on any line. Still, for 3 sales the result is 8.5. Make a prediction before running the code; most people read the code "according to its intention" and say 12.75.
What does the program in Example 1 print? (The program raises no error.)
def revenue(sales_count, price): total = 0.0 for turn in range(1, sales_count): total += price return total print(revenue(3, 4.25))
From this comes the first rule of the lesson: no error message does not mean the program is correct. The absence of a message only shows that Python could understand the code; it does not show that the code does what you want. The only way to know is to compare the result with a value you know is right.
How did we know the program was wrong? From the $12.75 in the register. So we had the right answer. The first step of debugging is exactly this: choose a small input and calculate the right result by hand, without running the code. This value is called the expected value. What the program gives is the actual value. If the two are the same, the program works correctly for that input; if they differ, there is an error.
You cannot find the expected value by asking the program. Since the program itself is suspect, its answer is not evidence. You do the calculation 3 sales × $4.25 = $12.75 on paper. Do not settle for a single input; write several inputs in a table and add the program's result next to them:
| Number of sales | Hand calculation (expected) | Program (actual) | Same? |
|---|---|---|---|
| 0 | 0.0 | 0.0 | ✓ |
| 1 | 4.25 | 0.0 | ✗ |
| 3 | 12.75 | 8.5 | ✗ |
| 5 | 21.25 | 17.0 | ✗ |
The table shows a pattern that a single try does not: each time the program counts exactly $4.25 less, that is, one sale missing. That it is right at 0 sales is a coincidence. If you had tried only 0, you would have thought the program was correct. So follow two rules when choosing inputs. First, choose numbers small enough that you can calculate by hand; you cannot verify the revenue of a real day with 300 sales in your head. Second, add edge values like 0 and 1; errors hide most at the edges. Testing with boundary values in lesson 7 was the same idea.
Change the number of sales below. For each value, the program writes both its own result and the expected value. See the difference yourself.
Change the number of sales: what is the difference between the program and the expected value?
Pick a value; predict the output first, then look.
1def revenue(sales_count, price):2 total = 0.03 for turn in range(1, sales_count):4 total += price5 return total67sales_count = 38print("Revenue:", revenue(sales_count, 4.25))9print("Expected:", sales_count * 4.25)
Revenue: 8.5 Expected: 12.75
Faded lines didn't run with this value. At 0 both are 0.0, but at 1, 3, and 5 the program is always $4.25 short. The difference is constant: exactly one sale is not counted each time. This pattern suggests a loop that runs one turn too few. You could not have seen this pattern with a single value.
Calculating the expected value by hand may seem like trouble, but if you skip this step, you search without knowing what you are looking for. The feeling "something is wrong somewhere" pushes you to change random lines; the sentence "it should be 4.25 for 1 sale, but it gives 0.0" gives you a concrete target.
printWe know the program is wrong and always counts one sale too few. But which line is wrong? To find that, you need to look inside the program. The simplest tool, and one that works everywhere, is print. In the suspicious area you put temporary lines that print intermediate values. When you run the program, these lines show the current value of the variables at every step. You compare each value with what you expected. The place where a value first departs from what is expected is the place of the error. This work is called tracing (the English word is debugging, "removing bugs").
Put a label like "TRACE:" at the start of the trace line. The label separates the trace lines from the program's real output and makes it easy to find which lines to delete when the work is done. After the label, you write the variables you want to watch, separated by commas.
Example 2 (case): A trace line in the loop
def revenue(sales_count, price): total = 0.0 for turn in range(1, sales_count): total += price print("TRACE:", turn, total) return total print(revenue(3, 4.25))
OutputTRACE: 1 4.25
TRACE: 2 8.5
8.5Because the trace line is inside the loop, it ran once on every turn. Now compare the output with what you expected. For 3 sales you expected three turns: TRACE: 1 4.25, TRACE: 2 8.5, TRACE: 3 12.75. But there are only two lines; the third turn is missing. The values increase correctly, what is missing is a turn. So the error is not in the addition line but in the line that decides how many times the loop runs: range(1, sales_count). Because the stop of range is not included, 3 is never produced. The fix is one of two ways: range(sales_count) (0, 1, 2: three turns again) or range(1, sales_count + 1) (1, 2, 3). After fixing it, you delete the trace line.
The Step through block on the site does the same job with a button: at every step it shows which line ran and the variable boxes. Step through the faulty revenue function below. Look at the turn and total boxes and count how many times the loop line is reached. When you work in a code editor on your own computer, a debugger does the same job; but print works everywhere, in every environment.
Run the code line by line: see which line runs next, the variable boxes and the output.
def revenue(sales_count, price): total = 0.0 for turn in range(1, sales_count): total += price return total print(revenue(3, 4.25))
Beware of one misconception: the error is not on the line where the wrong result is printed. The line print(revenue(3, 4.25)) only prints the number given to it; the line that produces the wrong number is much higher up. That is why you look not for the last line but for the place where the value was first corrupted.
Now let's move to the report's second wrong number: the latte count. The function looks at every letter in the order text and increases the counter whenever it sees L. Remember the counter pattern from lesson 12: the starting value of the counter is given before the loop.
Example 3 (case): Why is the counter always 1?
def latte_count(orders): for letter in orders: counter = 0 if letter == "L": counter += 1 print("TRACE:", letter, counter) return counter print(latte_count("LCLTL"))
OutputTRACE: L 1
TRACE: C 0
TRACE: L 1
TRACE: T 0
TRACE: L 1
1The trace lines speak clearly: the counter never goes past 1, and it drops to 0 on the letters C and T. The counter is reset on every turn, because the counter = 0 line is inside the loop. The moment it is 1 at the second L when it should be 2 is the moment the value first departs from what is expected. The result is 1 because the last letter is L: on the last turn the counter is reset and immediately becomes 1. What would happen if the last letter were not L? Predict first.
What does the faulty function in Example 3 (without the trace line) print for print(latte_count("LLLC"))?
def latte_count(orders): for letter in orders: counter = 0 if letter == "L": counter += 1 return counter print(latte_count("LLLC"))
This time you fix it. In the cell below, the function sits with its trace line. (1) Run it and read the TRACE lines: why is the counter always 0 or 1? (2) Fix the error by moving a single line. (3) Delete the TRACE line and run again; it should give 3 for "LCLTL".
Try it now· not graded; doesn't affect progress
When you suspect the type of a value, add the type to the trace line too: print("TRACE:", type(qty), qty). Remember from lesson 4: the string "3" and the number 3 look the same on the screen, but behave differently. type reveals this right away; there is an example of this in the Examples section.
Finally, trace lines are temporary. When the error is found and fixed, they are deleted. A trace line forgotten in the program mixes meaningless lines into the report; thinking "it does no harm, let it stay" is a common mistake.
Some logic errors are so common that you can guess the cause from the symptom. This table tells you where to look; you still confirm the exact answer by tracing.
| Symptom | Likely cause | Where you remember it from |
|---|---|---|
| The total is always one turn short or one turn over | The range limit (the stop is not included) | Lesson 10 |
| The counter or total is always 0 or 1 | The starting value is inside the loop | Lesson 12 |
The function looks at the first element and ends; it returns None on an empty input | The return is indented inside the loop | Lesson 14 |
| Only the last value is counted | The addition line is left outside the loop | Lesson 10 |
| Wrong tier at exactly the threshold value | >= should be used instead of > | Lesson 7 |
| The result is much bigger or much smaller than expected | Operator precedence, missing parentheses | Lesson 3 |
Let's see the last row with an example from outside the café. A student wrote a function that calculates the average of a midterm and a final grade.
Example 4 (outside the case): Grade average
def average(midterm, final): return midterm + final / 2 print(average(40, 80))
Output80.0Hand calculation: (40 + 80) / 2 = 60. The program says 80.0, bigger than expected. Python does the division first: final / 2 becomes 40.0, then the midterm is added and 80.0 comes out. The fix is parentheses: with return (midterm + final) / 2 the result is 60.0. There is again no error message; you noticed only thanks to the 60 you calculated by hand.
Now match the symptoms with their causes.
For each symptom, choose the most likely cause.
For each row, pick its match from the list, then check.
Real programs are not five lines like Example 1. In lesson 16 you split a program into functions; if the error is hiding in one of these parts, putting trace lines in all of them at once drowns the output. This is where narrowing down comes in: making the problem smaller step by step and reducing the suspicious area to a single part. Narrowing down has four tools.
First, shrink the input. Find the smallest input that still shows the error. In the revenue example, instead of a day with 300 sales, 1 sale is enough: expected 4.25, actual 0.0. With a small input there are fewer trace lines and you can check by hand.
Second, split the program. Call each function on its own with an input whose result you know by hand. Eliminate the parts that come out right; what remains is suspect. In lesson 16 we said "each part can be tested separately"; when debugging, you see the benefit of this.
Third, make a single change at a time. Change one thing, run, look at the table. If you change three lines at once and the result gets fixed, you cannot know which one fixed it; one might even have fixed it and another added a new error. Rewriting the code from scratch or changing random lines is a bad way for the same reason: you move on without understanding the error and may make the same error again in the new code.
Fourth, explain out loud. Read the code line by line, as if explaining it to someone: "Here I reset the counter, then I look at the letter..." Programmers call this the "rubber duck method"; explaining to a toy duck on the desk is enough. When you hear your own sentence, you often hear the error too.
Now let's look at the register's payment section. Three functions are connected: calc_subtotal calculates the basket's amount, calc_discount calculates the discount amount; total_due combines the two. The rule: 10 percent off an order of $10 and above.
Example 5 (case): Narrowing down across three functions
LATTE = 4.25 COOKIE = 2.00 TEA = 1.25 def calc_subtotal(latte, cookie, tea): return latte * LATTE + cookie * COOKIE + tea * TEA def calc_discount(amount): if amount > 10: return amount * 10 / 100 return 0 def total_due(latte, cookie, tea): subtotal = calc_subtotal(latte, cookie, tea) return subtotal - calc_discount(subtotal) print(total_due(0, 5, 0)) print(total_due(2, 1, 0))
Output10.0
9.45The second order is correct: 2 lattes and 1 cookie come to $10.50, and with 10 percent off, 9.45. But 5 cookies come to exactly $10.00 and by the rule $9.00 should be paid; the program says 10.0. Which of the three functions is guilty? Narrow it down: try each one on its own. print(calc_subtotal(0, 5, 0)) → 10.0; hand calculation 5 × 2.00 = 10.00, correct. print(calc_discount(10)) → 0; hand calculation 10 percent of 10 is 1.0, wrong. You do not need to look at total_due: it only combines the results of the other two.
Narrowing-down results: calc_subtotal(0, 5, 0) → 10.0 (expected 10.0), calc_discount(10) → 0 (expected 1.0). In which function is the error?
The fix is a single change: if amount >= 10: instead of if amount > 10:. Then you run the two orders again and look at the table: total_due(0, 5, 0) is now 9.0, and total_due(2, 1, 0) is still 9.45. The broken one got fixed and the correct one did not break. That is why, after a single change, you also try the old correct inputs again.
Put what you learned into a single method. Arrange the steps below in the correct order.
Put the debugging steps in order for a program that gives no error message but produces a wrong result.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Now try the method outside the café. Below is the faulty average function from Example 4. (1) Above the return line add print("TRACE:", final / 2) and run it: which operation is done first? (2) Fix it with parentheses. (3) Calculate the expected value for average(0, 100) by hand (50) and try the program. Do not forget to delete the TRACE line.
Try it now· not graded; doesn't affect progress
The power of this method is that it finds the error by evidence, not by guessing. At every step you have a comparison in your hand: the expected is this, the actual is that. When you find the place where the two part ways, you have found the place of the error too.
The quantity that came from the register screen stayed a string. The program raises no error, but when 3 items are doubled it prints 33 instead of 6. When type is added to the trace line, the problem is visible at once: qty is a string (str), and multiplying a string by 2 writes it next to itself twice. The fix is int(qty) * 2.
qty = "3" print(qty * 2) print("TRACE:", type(qty), qty)
Output33
TRACE: <class 'str'> 3A step counter adds up the steps of three days: 1000, 2000, and 3000. The hand calculation is 6000, the program says 3000. Because the total += steps line is left unindented, it is outside the loop; after the loop ends it runs once, with the steps of the last day only. This is the "only the last value is counted" row in the symptom table. The fix: indent the line with 4 spaces to bring it inside the loop.
total = 0 for day in range(1, 4): steps = day * 1000 total += steps print(total)
Output3000Forgetting trace lines in the program. The error was found, the fix was made, but the print("TRACE:", ...) line stayed inside the function. The program still runs without errors; but the report is now cluttered:
def revenue(sales_count, price): total = 0.0 for turn in range(sales_count): total += price print("TRACE:", turn, total) return total print("Revenue:", revenue(3, 4.25))
OutputTRACE: 0 4.25
TRACE: 1 8.5
TRACE: 2 12.75
Revenue: 12.75The calculation is right, but for someone reading the report, the first three lines are meaningless. If you use this function in another program, you carry the trace lines there too. The solution: once the error is fixed and the result is verified, delete all lines labeled TRACE. That is why you put a label: when you search for "TRACE" in the editor, you find all of them. One more thing: when fixing, do not change several lines at once. Even if the result gets fixed, you cannot know which change worked.
A trace line itself can also cause an error. If the comma after the label is forgotten in a hastily added trace line, this time the program does not run at all:
def revenue(sales_count, price): total = 0.0 for turn in range(sales_count): total += price print("TRACE:" turn, total) total (, revenue(3, 4.25))
print("TRACE:", ...) lines in the suspicious area; the error is at the place where a value first departs from what is expected; delete the trace lines when the work is done.Next lesson: In this lesson you calculated expected values by hand and compared them by eye; in the next lesson you will turn these comparisons into code with assert and repeat them with a single key after every change.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
Output File "<code>", line 5
print("TRACE:" turn, total)
^^^^^^^^^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?This error has nothing to do with the logic error you were looking for; it is a new syntax error you added while writing the trace line. Python also gives the solution at the end of the message: put a comma between "TRACE:" and turn. There must be a comma between every value you give to print. After adding a trace line, check that the program runs as before and only writes extra TRACE lines; only then start reading the trace lines.