Menu

Trace Tables

Tracing FOR Loops

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.

Flowchart of a for loop over range(3, 12, 3) that adds xy to pattern each pass, beside cards for passes with part 3, 6 and 9 and a dashed card showing 12 is never used.

Stagepartpattern after body
Before loopnot set(empty string)
Pass 13xy
Pass 26xyxy
Pass 39xyxyxy

Practise this