← Python lessons

Tracing Code

Tracing means following a program by hand, one executed statement at a time. Write down changing values and output before running the program. Trace what the code says, even if you think the author intended something else.

Use a trace table

Read this code without running it:

total = 0
for number in [2, 5, 3]:
    if number >= 3:
        total = total + number
print(total)

Keep columns for the loop item, condition result, running total and output.

Stepnumbernumber >= 3total after the stepOutput
Initialise——0—
First iteration2False0—
Second iteration5True5—
Third iteration3True8—
After the loop3—88

The first iteration skips the addition. print(total) runs once, after the loop. Now run this copy to check your prediction:

total = 0
for number in [2, 5, 3]:
    if number >= 3:
        total = total + number
print(total)

Check a while condition every time

counter = 1
while counter < 3:
    counter = counter + 1
    print(counter)

The condition is checked with counter equal to 1, 2 and finally 3. The body increments before printing, so the output is 2, then 3. The third check fails; it does not run the body again.

Follow function calls and returns

When a function is called, record its arguments, trace its body, then carry the returned value back to the caller. Defining a function does not run it. A return ends that call, even when it occurs inside a loop.

Your turn: predict before running

Make a trace table with number, the condition result and total. Predict the final output, then run the program and compare.

total = 1
for number in [2, 4, 1]:
    if number > 1:
        total = total * number
print(total)

Check your table: total starts at 1, becomes 2, then 8, then stays 8. The final output is 8. If your prediction differed, find the first row where it diverged instead of changing only the final answer.

See also: For Loops, While Loops, Nested Loops & Ifs, Debugging.


Practise this in the free Python course, where every exercise checks your code instantly.