Trace Tables
A for loop repeats its body once for each value it is given. With range(), those values are numbers, so tracing the loop means working out which numbers, in which order.
For a range() with a start, stop and step, begin at the start and keep adding the step until the next value would reach or pass the stop. The stop value is not included. A range from 2 to 9 with a step of 2 gives 2, 4, 6 and 8: four values, so four passes. Without a step, a range from 4 to 7 gives 4, 5 and 6. With only a stop value, a range of 3 gives 0, 1 and 2.
To trace the loop, make a new row for each pass, write the loop variable's value in that row, and update any variable that the body changes.
pattern = ""
for part in range(3, 12, 3):
pattern = pattern + "xy"
print(pattern)Output:
xyxyxy
The table shows each pass. The loop variable part takes three values, so the body runs three times, building up pattern two characters at a time. The stop value 12 never appears: the range ends before reaching it. The last entry shows the value left in pattern when the loop finishes.
| Stage | part | pattern after body |
|---|---|---|
| Before loop | not set | (empty string) |
| Pass 1 | 3 | xy |
| Pass 2 | 6 | xyxy |
| Pass 3 | 9 | xyxyxy |
Edexcel GCSE Computer Science · Trace Tables
Edexcel GCSE Computer Science · Count Controlled Iteration (For Loops)