Trace Tables
Before you trace any input or loop, write down the starting value of every variable in the first row of your trace table. That includes any counter or total that the algorithm sets to zero. If you skip this row, values can seem to appear from nowhere later.
When a statement does not change a variable, its previous value carries forward to the next row. In a trace table, an empty cell normally means the value is unchanged, not zero. So if a variable is still 5 from an earlier row, you can leave that cell blank and read it as 5. This keeps the table tidy without inventing new values, and it prevents values appearing or disappearing between rows.
Here is a short program. The variable bonus is set once and never changed, so its value carries forward through every loop row.
bonus = 5
score = 0
for question in range(1, 4):
score = score + 10 # 10 points for each question
print(score + bonus)Output:
35In the trace table, the first row records the starting values before the loop runs: score is 0 and bonus is 5. question has no value yet because the loop has not started, so its cell is blank. Inside the loop, score changes each time, but bonus stays at 5, so its cells are left empty and read as 5.
| score | bonus | question | output |
|---|---|---|---|
| 0 | 5 | ||
| 10 | 1 | ||
| 20 | 2 | ||
| 30 | 3 | ||
| 30 | 35 |
The output column is only filled when print() actually runs, which is after the loop has finished. The final output is 35, not 0, because the carried-forward bonus of 5 is added to the final score of 30. The empty cells in the last row are read as unchanged too: bonus is still 5 and question is still 3.
Edexcel GCSE Computer Science · Trace Tables