← All notes

Python · Exam tips

How to trace a for loop, line by line

Published
Reading time
3 minutes

The problem

Most “what is the output?” questions go wrong for one reason: we read the code like a sentence instead of running it like a machine. The fix is simple. Trace it on paper, one pass at a time.

Here is a question in the style of the HS 2026 Semester 3 COMS paper. What does this print?

for letter in "Computer Science":
    if letter == "e":
        continue
    print(letter, end="")

Three rules for tracing

  1. One row per pass. The loop variable takes one new value each time. Give each value its own row.
  2. Check the condition before acting. Decide whether letter == "e" is true first, then follow the branch it chooses.
  3. Know what continue does. It skips the rest of this pass and jumps to the next letter. It does not stop the loop.

The trace

Here end="" means nothing is added after each letter, so everything prints on one line. In the last column, _ stands for the space in the text.

letter   is it "e"?     printed so far
C        no             C
o        no             Co
m        no             Com
p        no             Comp
u        no             Compu
t        no             Comput
e        yes, skip      Comput
r        no             Computr
(space)  no             Computr_
S        no             Computr_S
c        no             Computr_Sc
i        no             Computr_Sci
e        yes, skip      Computr_Sci
n        no             Computr_Scin
c        no             Computr_Scinc
e        yes, skip      Computr_Scinc

The output is Computr Scinc. Every lowercase e is gone, and nothing else is.

A quick check

Change continue to break. What prints now? Trace it the same way: the loop runs normally until the first e, then stops completely. The output is Comput.

Now delete end="" from the print line. Each letter is printed on its own line, because print adds a new line by default.

The habit to keep

When I am unsure, I do not guess from the shape of the code. I draw the table. It takes a minute, and it turns a confusing question into sixteen small, easy ones.

I explain the whole paper, with the reasoning for every question, in this video on The Logic Room.