Unit 11.1A · Term 1

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.

Read codeone statement
→
Record statenew values
→
Compareexpected vs actual

Trace Table Method

1Create columns

Use one column for each changing variable and an Output column when needed.

2Follow execution

Use the real control flow. Selection may skip lines; loops may repeat them.

3Record changes

Write values exactly as Python calculates them.

4Record output

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.

1x = 3
2y = 2
3total = 0
4while x > 0:
5    total = total + y
6    x = x - 1
7print(total)
x—
y—
total—
Press Next statement to begin.

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
The initial row is provided. Complete the remaining rows.

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.

Predict the final value of s and exact output first.

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

Classify the most important error shown.

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

Traceback (most recent call last):
File "program.py", line 4, in <module>
answer = 10 / number
ZeroDivisionError: division by zero
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

Reproducesame failing input
→
Locatesuspicious line/state
→
Tracerecord values
→
Fixchange the cause
→
Retestnormal + edge cases

Bug Hunt

1num = input("Enter a number: ")
2total = 0
3for i in range(1, num):
4    total += i
5    print("Sum:", totl)

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)
Input
10
20
30
Expected vs Actual
Expected: 20.0
Actual:   30.0
Which line causes the logic error?
Compare the expected operation with the actual formula.

Worked Examples

Choose an example:

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

Remember

Name the three main error types and state when each is detected.

Understand

Explain why pritn("Hello") produces a runtime NameError rather than a syntax error.

Understand

State the purpose of an Output column in a trace table.

Apply

Create a complete trace table for n=4; result=1; while n>1: result*=n; n-=1; print(result).

Apply

Fix the average program: total=0; for i in range(3); n=input(...); total+=n; avg=total/2.

Apply

Given a traceback ending in ZeroDivisionError, describe the order in which you would investigate it.

Analyze

Trace s=""; for i in range(1,5): if i%2==0: s+=str(i); else: s+="*". Show every value of i and s.

Create

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
i=0 → x=3, y=2 i=1 → x=5, y=3 i=2 → x=8, y=4 after loop → output 8

Q2: Classify the error and explain why. [2] age = int("sixteen")

Reveal marking points
Runtime error / ValueError. The string cannot be converted to an integer.

Q3: Identify and fix the error. [2]

length = 8 width = 5 area = length + width print(area)
Reveal marking points
Logic error. Replace + with *: area = length * width

Q4: Which traceback line should you normally read first, and why? [2]

Reveal marking points
Read the final line first because it gives the exception type and message. Then use the lines above to locate the source statement and call path.

Self-Check Quiz

Eight quick checksClick each answer to reveal
1. What type of error is pritn instead of print?
Click to reveal answer
2. Which error type can give the wrong answer without crashing?
Click to reveal answer
3. What should a trace table record when print() executes?
Click to reveal answer
4. What should you normally read first in a traceback?
Click to reveal answer
5. What error does int("hello") cause?
Click to reveal answer
6. Why is expected output useful during debugging?
Click to reveal answer
7. Why add temporary print() statements?
Click to reveal answer
8. What should you do after fixing a bug?
Click to reveal answer