Skip to main content

Trace tables explained

6 min readUpdated

A trace table records how the values of variables change as an algorithm runs, one line at a time. Exams use them to test whether you can read code, and they are also the fastest way to find a bug by hand.

How to set one up

  1. Make one column for every variable, one for any condition you need to check, and one for output.
  2. Add a new row each time a value changes.
  3. Only fill a cell when that value changes; leave the rest blank or copy the value, as your exam expects.

Worked example

Code to tracepython
total = 0
count = 1
while count <= 4:
    total = total + count
    count = count + 2
print(total)
counttotalcount <= 4Output
10True
31True
54False
4

The loop adds 1, then 3. When count becomes 5 the condition is false, the loop ends and 4 is printed.

Tracing a loop over a list

python
marks = [7, 3, 9, 4]
highest = marks[0]
for m in marks:
    if m > highest:
        highest = m
print(highest)
mm > highesthighestOutput
7
7False7
3False7
9True9
4False9
9

Tips that save marks

  • Work one line at a time; never jump ahead because you think you know the answer.
  • Check the loop condition every time round, including the last time when it is false.
  • Watch integer division (//) and remainder (%).
  • Write outputs in the order they happen.

Using trace tables to debug

When your program gives the wrong answer, trace it with a small input. The row where a value first goes wrong points to the faulty line. This works especially well for off-by-one errors and wrong conditions.

Frequently asked questions

Do I need to repeat values that did not change?

It depends on the mark scheme. Most accept either; a new row only when something changes is the clearest style.

What if there is a nested loop?

Give each loop variable its own column and trace the inner loop fully for each step of the outer loop.

Can trace tables be used for recursion?

Yes, but a call table showing each call and its return value is usually clearer.

Practise this, step by step

Short lessons with quizzes, practice and interview questions, from your first program to job-ready.

Python Programming course: syllabus and 1:1 mentoringCore Python from zero to functions, collections, files, OOP and algorithms.