Level 1
0 / 100 XP

Reading and tracing code

Before you can fix a program, you have to know what it actually does — not what you hoped it would do. Tracing means stepping through code line by line, like the computer would, and tracking each variable's value. It's the single most useful debugging skill.

Trace by tracking variables

Read one line at a time and write down what each variable holds after that line runs:

Python
total = 0 for n in [2, 4, 6]: total = total + n print(total)

Trace it:

  • Start: total = 0
  • Loop n=2: total = 0 + 2 -> 2
  • Loop n=4: total = 2 + 4 -> 6
  • Loop n=6: total = 6 + 6 -> 12
  • Print: 12
Python
total = 0 for n in [2, 4, 6]: total = total + n print(total) # 12

Predict the output, then run it

Cover the comment and predict what this prints before reading on:

Python
word = "python" print(word[0]) # p print(word[-1]) # n print(word[1:4]) # yth print(len(word)) # 6

Predicting first turns running the code into a quick self-check. When your prediction is wrong, you've found a gap in your understanding — exactly what you want to catch early.

Spot the bug

Many bugs are tiny. Trace carefully and they jump out:

Python
def is_even(n): return n / 2 == 0 # BUG: / gives a float; 4/2 is 2.0, never 0 print(is_even(4)) # False (we expected True)

The fix is one character — use remainder logic instead:

Python
def is_even(n): return n % 2 == 0 # remainder is 0 for even numbers print(is_even(4)) # True

Common bugs to watch for: using = (assign) where you meant == (compare), off-by-one in slices and ranges, indenting a line into or out of a loop, and forgetting that string methods return a new string instead of changing the original.

Key takeaways

  • Trace code by tracking each variable's value line by line.
  • Predict output before running so running becomes a self-check.
  • Look for classic bugs: = vs ==, off-by-one, wrong indentation,…