Skip to content
All teaching guides

Teach loops with code tracing

Ask students to predict a program’s output and track a changing variable before they run it.

By Joe Mazzone · Introductory programming

What students should learn

Students can explain how a loop changes a running total, not just name the final answer.

Use a short loop with one changing variable. In this example, total starts at 0 and adds 1, then 2, then 3. The final value and printed output are both 6.

total = 0
for n in [1, 2, 3]:
    total += n
print(total)

Try the block

Loading the lesson block…

A teaching sequence

  1. Predict before running. Show the program without its output. Ask students to write what it prints and the final value of total. Give them a few minutes on their own before you discuss.
  2. Explain each update. Ask for total after each pass through the loop: 1, 3, then 6. If a student says 3, ask whether the program replaces total or adds to it.
  3. Change one thing. Replace the list with [2, 4, 6] and ask for a new prediction. Then move print(total) inside the loop and ask again. Students should see the difference between the final value of total and everything the program prints.

What to assess

Set the Code Tracing block’s expected output to 6 and total to 6. Then add an Open Response asking why total += n is different from total = n. The trace is graded automatically; grade the explanation with a rubric item.

A follow-up task

Next, give a small Code Editor task where students write a loop themselves. Reading a loop correctly doesn’t mean they can write one yet.

Build it in your course