Python trace tables: worked examples and practice
Follow changing variables through loops and selection, then test your understanding with original self-check questions.
Worked guide · no account needed
What is a Python trace table?
A trace table records how selected variables change as a program runs, one executed step at a time. It is useful when an exam asks you to predict output, dry-run a loop, or explain why a program behaves unexpectedly. You do not need to execute Python to fill one in, but running the code afterwards helps test your reasoning.
Example 1: trace a count-controlled loop
total = 0
for number in range(1, 4):
total = total + number
print(total)
range(1, 4) gives 1, 2, 3; the stopping value 4 is excluded. Record the values after each addition:
| Iteration | number | total before | total after |
|---|---|---|---|
| 1 | 1 | 0 | 1 |
| 2 | 2 | 1 | 3 |
| 3 | 3 | 3 | 6 |
Final output: 6. The program prints once, after the loop has finished.
Example 2: trace selection inside a loop
points = 0
for value in [2, 5, 8]:
if value > 4:
points += 1
print(points)
| Value | Greater than 4? | Points after check |
|---|---|---|
| 2 | No | 0 |
| 5 | Yes | 1 |
| 8 | Yes | 2 |
Final output: 2. The loop executes three times, but the counter only increases twice.
Example 3: trace a condition-controlled loop
count = 1
while count < 5:
count = count * 2
print(count)Write the values in order: initial count = 1, then 2, then 4, then 8. At 8, the condition count < 5 is false.
Output: 8. A while loop can leave the variable beyond the boundary; it does not automatically stop exactly at 5.
Three independent questions
- Trace
result = 1, thenfor n in range(1, 4): result *= n. What prints at the end? - A program loops over
[1, 3, 6, 8]and increases a counter when a number is even. What is the final counter? n = 10;while n > 3: n -= 3. What is the finaln?
Reveal answers and reasoning
1 → 1 → 2 → 6; output 6.- Two values (6 and 8) are even; output 2.
10 → 7 → 4 → 1; output 1.
Common mistakes when filling trace tables
- Including the end value of
range()when it is excluded. - Recording the value before an assignment as though it were the value after it.
- Skipping iterations that do not change the tracked variable.
- Confusing the number of iterations with the number of
print()calls. - Assuming a
whileloop must terminate at the boundary, rather than just pass the next condition check.
