Learn Python · lesson 23 of 60 · about 8 minutes
Tracing and Debugging Loops
Find Sam's best run of good nights: predict a loop step by step on paper, and fix off-by-one mistakes.
What you'll learn
- Trace variables through each loop pass
- Spot off-by-one errors
- Use print() to debug
Good nights in a row
One good night is nice, but a run of them is what really counts. Sam wants the best run of the week: for 6787566 that's 3 good nights in a row. The loop needs two numbers: run, which grows on a good night and goes back to 0 on a short one, and best_run, the longest run so far. A loop like this is easy to get slightly wrong, so it's a good one to trace.
Tracing
Tracing means stepping through a loop like the computer does, writing down each variable after every pass. It's the most reliable way to understand a loop that isn't doing what you expect.
| pass | i | total |
|---|---|---|
| start | | 0 |
| 1 | 1 | 1 |
| 2 | 2 | 3 |
| 3 | 3 | 6 |
The loop traced above
total = 0
for i in range(1, 4):
total += i
print(total)Output
6Step through it: the run and the best run
run = 0
best_run = 0
for hours in "7768":
if int(hours) >= 7:
run += 1
if run > best_run:
best_run = run
else:
run = 0
print(best_run)Output
2Off-by-one errors
The most common loop bug is going round one time too many or too few, usually because range stops *before* its end value or a < should be <=.
When unsure, add a temporary print inside the loop to see each value, then remove it.
Debug print shows the problem
for i in range(1, 5):
print("i is", i)Output
i is 1
i is 2
i is 3
i is 4Tip
The indexes of a string go from 0 to len(text) - 1. range(len(text)) gives exactly those, so text[i] never runs past the end.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.