Python Foundations & The 6-Step Method · Lesson 5 of 5

Hand-Tracing — Where Logic Actually Grows

Reading code and understanding code are not the same thing. Hand-tracing is the one habit that grows your logic fastest — and it's just pen and paper.

By Shahriyar · Updated

The idea, in one line

Be the computer. On paper, keep a little table of every variable and update it one line at a time, exactly as the code would.

What it means

Hand-tracing forces you to admit what each line really does — no hand-waving, no "it probably works". If you can trace it, you understand it.

How to do it

  1. Draw a column for each variable.
  2. Walk the code top to bottom; when a line changes a value, cross out the old one and write the new.
  3. At a loop, note which item you're on. At an if, note True/False and which branch you took.
  4. When you hit return, the value you've written down is your predicted answer.

See it work

▸ trace_me.py
# Trace this BY HAND before trusting the answer below.
# Keep a table: total, then n each time through the loop.
def total_failures(codes):
    total = 0
    for n in codes:
        if n >= 400:
            total = total + 1
    return total

total_failures([200, 404, 500, 200])

# Trace table:
# start           total = 0
# n = 200   >=400? no    total = 0
# n = 404   >=400? yes   total = 1
# n = 500   >=400? yes   total = 2
# n = 200   >=400? no    total = 2
# return 2

Read the table top to bottom: total starts at 0 and only ticks up when a code is 400 or more. Two codes qualify, so the answer is 2 — and you knew that before running a thing.

Advanced — a trace is a test you ran in your head

Here's why this pays off so much. A trace is really a by-hand test case. If your trace predicts 3 and the program prints 4, you've found the exact line where your idea of the code and the real code disagree. Spotting that gap is the whole skill of debugging — so every trace you do is debugging practice in disguise.

The house method — practiced daily on solved problems

All lessons in Python Foundations & The 6-Step Method

  1. Variables, Types, Control Flow & Functions
  2. Lists, Dicts, Sets & Tuples — When and Why
  3. String Manipulation Patterns
  4. The 6-Step Method — A Worked Example
  5. Hand-Tracing — Where Logic Actually Grows