Debugging: finding and fixing mistakes
🌍 In real life. When a motorbike won't start, a good mechanic doesn't replace parts at random. They ask what happens when you press the starter, check one thing (is there fuel?), then the next (is the spark plug working?), and each check narrows down where the fault can be. When they find it, they fix that one thing and try again.
Fixing a program works the same way, and it has a name: debugging. Now that your programs have loops, mistakes can hide inside a lap you never see, so it's time to learn to hunt for them on purpose.
The idea in one sentence: debugging means finding the exact place where your program does something different from what you expected, by reading the error, looking at the values, and checking one step at a time.
Its words:
- bug: a mistake in a program
- traceback: Python's error report, ending with the error's name and reason
- print debugging: adding temporary
print()lines to see values as the program runs - tracing (or a dry run): running the program by hand, writing down each variable after every step
Step by step, a debugging routine:
- Make it happen again with a small input you can check by hand.
- Is there an error message? Read its last line and go to the line number.
- No error, wrong answer? Print the values inside the loop, or trace it by hand.
- Find the first step that goes wrong. That's where the bug is.
- Fix one thing, run again, and test a few inputs, including the edges (0, 1, the last value).
Three kinds of bugs.
- Syntax errors: the code breaks Python's writing rules, so nothing runs at all. The message points at the line.
- Runtime errors: the program starts, then crashes on some line, with a traceback. Often it's only one lap that crashes, and the question is which lap.
- Logic errors: no message at all; the program runs and prints a wrong answer. These are the hardest, because Python can't know what you meant.
Reading a runtime error in a loop. Run this. The traceback names line 3, but line 3 ran fine on several laps before it crashed. Which value of n broke it?
total = 0
for n in range(3, -1, -1):
total += 12 // n
print(total)Print debugging. Add one temporary line that shows the value at the start of every lap. Now the output tells the story: the laps for 3, 2 and 1 worked, and the crash came on the lap where n was 0. The fix is to stop the range before 0. When the bug is fixed, delete the debugging print.
total = 0
for n in range(3, -1, -1):
print("n is", n)
total += 12 // n
print(total)Tracing by hand, for a logic error. This program should print the average of 1, 2, 3 and 4, which is 2.5. It prints 2.0, and there's no error to read. So trace it: follow the loop lap by lap, writing down n, total and count after each one.
- lap 1: n = 1 → total 1, count 1, then n becomes 2
- lap 2: n = 2 → total 3, count 2, then n becomes 3
- lap 3: n = 3 → total 6, count 3, then n becomes 4
- check:
4 < 4is False, so the loop stops: 4 was never added
The animation shows the same thing. Watch the last check:
total = 0
count = 0
n = 1
while n < 4:
total += n
count += 1
n += 1
print(total / count)Debuggers: watching without print. On your own computer, an editor like VS Code has a debugger. Click left of a line number to set a breakpoint, run with debugging, and the program pauses on that line. You can look at every variable, then step one line at a time: tracing by hand, done for you. Python has one built in too: a line with breakpoint() pauses the program in the terminal debugger, pdb. Type p total to print a variable, n to run the next line, and c to carry on. (The Python in this course runs inside your browser and can't pause like that, so here print debugging and the code tracker under each animation do the job.)
One more print trick: print(f"{n=}") shows the name and the value together, n=3.
Why this works. A bug is always at one particular step: before it, every value is what you expected; after it, something is wrong. Printing or tracing shows you the values step by step, so instead of staring at the whole program, you only have to find the first step that surprises you.
Mistakes and edge cases.
- Changing many things at once. If it then works, you don't know which change fixed it, and the others may have added new bugs.
- Guessing instead of looking. Print the value before you decide what it is.
- Reading the top of the traceback. The last line holds the error; the line just above it is where it happened.
- Testing one input only. Off-by-one bugs hide until you try the edges: 0, 1 and the last value.
- Leaving debugging prints in. They change the output, and task tests compare the output exactly.
Quiz
A program runs without any error message but prints the wrong answer. What kind of bug is it?
- A logic error
- A syntax error
- A runtime error
These debugging prints show each lap. What do they print?
x = 1 for i in range(3): x = x * 2 print("lap", i, "x is", x)This should print the average of 1, 2, 3 and 4, which is 2.5. It prints 2.0. Which line has the bug?
total = 0 count = 0 n = 1 while n < 4: total += n count += 1 n += 1 print(total / count)Which part of a traceback should you read first?
- The last line: the error's name and reason
- The first line, Traceback (most recent call last)
- Any line; they all say the same
This should print 6 (1 + 2 + 3), but it prints 3. Which line has the bug?
for n in range(1, 4): total = 0 total += n print(total)breakpoint() has paused your program in pdb. What does typing n do?
- Runs the next line, then pauses again
- Prints the variable called n
- Ends the program
Coding tasks
Fix the crash. This program counts the digits of a whole number (for
12345it prints5), but it won't even start. Read the error, find the line, and fix it.Fix the wrong answer. This program should add up the even numbers from 1 to n, including n. For n = 10 the answer is 2 + 4 + 6 + 8 + 10 = 30, but it prints 20. There's no error message: trace it or print
ito find the bug.Find the bug with prints. This program reads numbers until the user types 0, then prints their average. For 4, 6, 8 and then 0 it should print
6.0, but it prints18.0. Printcountinside the loop to see what's going wrong, then fix it (and remove your debugging print).