Tracing & Debugging
Tracing means stepping through program code and recording how variables and output change. Debugging means locating, understanding and fixing errors. These are general techniques you can apply to any program.
Learning Objectives
- 11.1.2.3 Trace program code
- 11.1.2.6 Debug a program
Connection to the previous lesson
You already traced nested loops. Now we generalise the technique to assignments, selection, loops, accumulators and complete programs. We will not repeat the nested-loop grid mechanics here.
Trace Tables
Craig'n'Dave Cambridge IGCSE — trace tables and dry-running algorithms.
Conceptual Anchor
The Detective Analogy
Tracing code is like being a detective examining evidence step by step. A trace table is your evidence notebook: you record variable values and output as execution progresses. Debugging is the investigation that finds the line or state that caused the problem.
Trace Table Method
Use one column for each changing variable and an Output column when needed.
Use the real control flow. Selection may skip lines; loops may repeat them.
Write values exactly as Python calculates them.
Whenever print() executes, add its result to the Output column.
How many rows?
A row may represent a statement execution, one loop iteration, or a meaningful state change depending on the question. The important rule is consistency: do not skip a value change that is needed to explain the result.
Worked Trace Table
x = 5
y = 3
total = 0
while x > 0:
total = total + y
x = x - 1
print(total)| Step | x | y | total | x > 0? | Output |
|---|---|---|---|---|---|
| init | 5 | 3 | 0 | True | |
| 1 | 4 | 3 | 3 | True | |
| 2 | 3 | 3 | 6 | True | |
| 3 | 2 | 3 | 9 | True | |
| 4 | 1 | 3 | 12 | True | |
| 5 | 0 | 3 | 15 | False | 15 |
Statement-by-Statement Tracer
Step through a complete program and watch the current line, variables and output change together.
———Trace Table Practice
Guided Practice
n = 4
result = 1
while n > 1:
result = result * n
n = n - 1
print(result)| Step | n | result | n > 1? | Output |
|---|
Independent Practice
s = ""
for i in range(1, 5):
if i % 2 == 0:
s = s + str(i)
else:
s = s + "*"
print(s)Decide which columns you need before opening the template.
Three Types of Errors
Syntax Error
Python cannot parse the program because a language rule has been broken.
print("Hi"
Runtime Error
The program starts, but an invalid operation occurs while it is running.
10 / 0
Logic Error
The program runs, but the algorithm or formula produces the wrong result.
area = length + width
Error Classifier
Common Python Errors
SyntaxError
Missing colon, bracket or quote. Check punctuation and syntax.
IndentationError
Invalid or inconsistent indentation.
NameError
An undefined or misspelled name is used.
TypeError
An operation receives an inappropriate type.
ValueError
Example: int("abc").
ZeroDivisionError
Division or modulo by zero.
IndexError
A sequence index is outside valid bounds.
Reading a Python Traceback
Click a traceback line. Recommended order: 1. Read the final line. 2. Identify the error type. 3. Find the line number. 4. Inspect the source line. 5. Work backwards to find why the value became invalid.
Practical rule
Start at the bottom to identify the exception, then use the file and line information above it to locate the failing statement. In longer tracebacks, earlier lines show the chain of function calls that led there.
Systematic Debugging
Bug Hunt
Select a suspicious line
Click a line to investigate it.
Expected vs Actual Output
# Intended: average of 3 numbers
total = 0
for i in range(3):
n = int(input("Number: "))
total += n
average = total / 2
print(average)10 20 30
Expected: 20.0 Actual: 30.0
Worked Examples
Pitfalls & Common Errors
Logic errors may not crash
Compare actual output with a known expected result and trace the program to find where values first diverge.
Skipping important trace steps
A trace table is evidence. Do not skip a state change needed to explain the final result.
Confusing runtime and syntax errors
A NameError occurs during execution. A syntax error prevents Python from
successfully parsing the program.
Fixing without retesting
Always rerun the failing case and at least one normal case after a fix.
Pro-Tips for Exams
Trace Table Tips
- Create columns for every changing variable required by the question.
- Record output exactly when the print statement executes.
- Follow the real control flow: selection may skip statements and loops may repeat them.
- Keep types accurate — for example,
/can produce a float. - Do not jump straight to the final answer when intermediate states are required.
Debugging Strategy
- Read the error message and identify its type.
- Locate the line mentioned by the traceback.
- Trace suspicious variables or use temporary debug prints.
- Compare actual output with an expected result you can calculate manually.
- Retest after every fix.
Graded Tasks
Name the three main error types and state when each is detected.
Explain why pritn("Hello") produces a runtime NameError
rather than a syntax error.
State the purpose of an Output column in a trace table.
Create a complete trace table for
n=4; result=1; while n>1: result*=n; n-=1; print(result).
Fix the average program:
total=0; for i in range(3); n=input(...); total+=n; avg=total/2.
Given a traceback ending in ZeroDivisionError, describe the order in
which you would investigate it.
Trace s=""; for i in range(1,5): if i%2==0: s+=str(i); else: s+="*".
Show every value of i and s.
Write a deliberately buggy program with one syntax error, one runtime error and one logic error. Then provide the corrected version with explanations.
Exam Practice
Q1: Complete the trace table. [4]
x = 2
y = 1
for i in range(3):
x = x + y
y = y + 1
print(x)| i | x | y | Output |
|---|---|---|---|
| 0 | ? | ? | |
| 1 | ? | ? | |
| 2 | ? | ? | |
| after loop | ? | ? | ? |
Reveal completed trace
Q2: Classify the error and explain why. [2]
age = int("sixteen")
Reveal marking points
Q3: Identify and fix the error. [2]
length = 8
width = 5
area = length + width
print(area)Reveal marking points
Q4: Which traceback line should you normally read first, and why? [2]
Reveal marking points
Self-Check Quiz
pritn instead of
print?int("hello") cause?