Python Debugging Basics
Debugging is the step-by-step search for a bug in code. A bug is a mistake that makes code misbehave.
Label every debug print
A label tells you which value you are seeing.
scores = [10, 20, 30]
print("scores:", scores)
print("count:", len(scores))Prints reveal the wrong value
These prints show a count that cannot be right.
total = 10 + 20 + 30
count = 2
print("total:", total)
print("count:", count)Test a tiny case first
Use small numbers with a simple expected result.
print((10 + 20) / 2)Compare expected and real
This average matches the answer you expect.
average = (10 + 20 + 30) / 3
print("average:", average)Example
scores = [10, 20, 30]
total = sum(scores)
count = 2
print("total:", total)
print("count:", count)
average = total / len(scores)
print("average:", average)Key points
- Use labelled prints so you know which value is which
- Read your code aloud to spot lines that sound wrong
- Shrink the problem until the failing example is tiny
- Ask what you expected, then compare what happened
In this example, two labelled prints inspect a broken average. The scores add up to a total of 60. The first print shows that total, and it looks right. The count variable holds 2, and the second print shows it. But the list holds three scores, so count is wrong. That print found the bug. The last line divides by len(scores) instead. The average now prints as 20.0, which is correct.
Note
pdb is the built-in Python debugger.
Try it when prints stop being enough.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
A program gives the wrong average. What is a good first debugging step?