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:
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
Predict the output, then run it
Cover the comment and predict what this prints before reading on:
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:
The fix is one character — use remainder logic instead:
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,…
No comments yet. Add the first comment to start the discussion.