Trace Tables
A while loop repeats its body while a condition is true. To trace it, test the condition before each iteration using the current values of the variables. If the condition is true, trace the loop body and record every change. Then test the condition again. When it is false, stop tracing the loop body and continue with the statement after the loop.
In the program below you start with £1 saved and put away another £2, saving again only while you have £5 or less. The trace table shows the condition test before every pass, and the final false test that ends the loop.
saved = 1
while saved <= 5:
saved = saved + 2
print(saved)Output:
7
| saved | saved <= 5 | What happens |
|---|---|---|
| 1 | True | Body runs: saved becomes 1 + 2 = 3 |
| 3 | True | Body runs: saved becomes 3 + 2 = 5 |
| 5 | True | Body runs: saved becomes 5 + 2 = 7 |
| 7 | False | Body is skipped; continue after the loop |
After the false test, saved still holds 7, so the print() after the loop outputs 7. The false row is not an extra iteration: its body never runs. Recording it shows exactly why the loop stopped and where tracing continues.
Edexcel GCSE Computer Science · Trace Tables
Edexcel GCSE Computer Science · Condition Controlled Iteration (While Loops)