I1 · Python Programming for AI

Tracing an Algorithm by Hand

Tracing, also called a dry run, means following an algorithm step by step by hand and recording the value of each variable after every step, usually in a trace table. It predicts the output and reveals errors before the program is run.

8 min Intermediate Jump to the activity

What you need: The earlier topics of this module.

Definition

Can you know what a program will output before the computer runs it?

Tracing, also called a dry run, means following an algorithm step by step by hand and recording the value of each variable after every step, usually in a trace table. It predicts the output and reveals errors before the program is run.

In simple words

Become the computer. Make a column for each variable. Go through the steps one at a time, and every time a value changes, write the new value on a new row. When you reach the end, the last row tells you the answer.

Why it matters

Tracing is how programmers understand code they didn't write and find bugs they can't see. It builds the exact mental model of a computer that every later topic, from loops to neural networks, relies on.

How it works

total ← 0
for each mark in [12, 7, 15, 5]:
    total ← total + mark
output total
Stepmarktotal
Start–0
1st loop1212
2nd loop719
3rd loop1534
4th loop539

Try it yourself

Trace a loop that totals a list of marks

Fill in the value of total after each step, then check your trace.

Trace a search for the largest mark

Now trace an algorithm with a decision inside the loop.

Common mistakes

  • Skipping a step in your head instead of writing every row.
  • Updating a variable with its old value from two steps ago.
  • Tracing with huge inputs. Small ones find the same bugs faster.

Check yourself

Question 1

1. total starts at 0 and adds 3, then 4, then 5. Its final value is…

Question 2

2. What does a trace table record?

Question 3

3. largest starts at 12, then the marks 7, 15, 5 are checked. Final largest?

Summary

  • Tracing means running an algorithm by hand, step by step.
  • A trace table has a column per variable and a row per change.
  • It predicts output and pinpoints bugs before running anything.

Finished reading?