Unit 11.1A · Term 1

Tracing & Debugging

Tracing means stepping through code line by line, recording how variables change — a critical exam skill. Debugging is the process of finding and fixing errors. Together, they make you a confident, effective programmer.

Learning Objectives

  • 11.1.2.3 Trace program code
  • 11.1.2.6 Debug a program

Lesson Presentation

11.1A-lesson-08-tracing-debugging.pdf · Slides for classroom use

Conceptual Anchor

The Detective Analogy

Tracing code is like being a detective examining a crime scene step by step. A trace table is your evidence notebook — you record every variable change as it happens. Debugging is finding which "suspect" (line of code) caused the "crime" (bug). Methodical, line-by-line investigation always beats random guessing.

Rules & Theory

Trace Table Method

A trace table has one column per variable plus an Output column. You add a new row each time a variable changes value.

# Code to trace: 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

Three Types of Errors

Error Type When Detected Cause Example
Syntax Error Before running Violates Python rules print("hi" — missing )
Runtime Error While running Impossible operation 10 / 0 — ZeroDivisionError
Logic Error After running Wrong algorithm/formula Using + instead of *

Common Python Errors

Error Name Cause Fix
SyntaxError Missing colon, bracket, quote Check punctuation
IndentationError Wrong whitespace Use consistent 4-space indentation
NameError Undefined variable Check spelling, declare before use
TypeError Wrong type in operation Use int(), str() conversion
ValueError Invalid conversion int("abc") — validate input
ZeroDivisionError Division by zero Check divisor != 0
IndexError Invalid list/string index Check bounds

Reading a Traceback

Python tracebacks read bottom to top. The last line tells you the error type and message. The line above it shows the exact line number and code that caused the error. Always start reading from the bottom!

Worked Examples

1 Trace Table — Swapping Variables

a = 10 b = 20 temp = a a = b b = temp print(a, b)
Step a b temp Output
1 10 20
2 10 20 10
3 20 20 10
4 20 10 10
5 20 10

2 Finding and Fixing Bugs

# BUGGY CODE — Find 3 errors: num = input("Enter a number") # Bug 1: missing colon in prompt total = 0 for i in range(1, num): # Bug 2: num is a string! total += i print("Sum:", totl) # Bug 3: typo "totl" # FIXED CODE: num = int(input("Enter a number: ")) # Fix 1: added ": ", Fix 2: int() total = 0 for i in range(1, num + 1): # Fix: include num in range total += i print("Sum:", total) # Fix 3: fixed typo, moved outside loop

3 Trace — Fibonacci Sequence

a = 0 b = 1 for i in range(6): print(a, end=" ") a, b = b, a + b
i a (before) b (before) Output a (after) b (after)
0 0 1 0 1 1
1 1 1 1 1 2
2 1 2 1 2 3
3 2 3 2 3 5
4 3 5 3 5 8
5 5 8 5 8 13

Output: 0 1 1 2 3 5

4 Debugging Strategy — print() Debugging

# If you can't find a bug, add print() statements: def average(numbers): total = 0 for n in numbers: total += n print(f"DEBUG: n={n}, total={total}") # Temporary debug print avg = total / len(numbers) print(f"DEBUG: final total={total}, count={len(numbers)}") return avg result = average([10, 20, 30]) print("Average:", result) # Remove debug prints when the bug is fixed!

Pitfalls & Common Errors

Logic Error — Hardest to Find

Logic errors don't crash the program — they just give wrong results. The code runs fine, but the answer is incorrect. Only trace tables and careful testing reveal them.

Skipping Steps in Trace Tables

In exams, you must show every variable change, not just the final values. Each row should represent one iteration or one statement execution.

Confusing Error Types

A NameError is a runtime error (program crashes), not a syntax error. Syntax errors prevent the program from running at all. Runtime errors occur while the program is running.

Pro-Tips for Exams

Trace Table Tips

  • Draw columns for every variable mentioned + an Output column
  • Execute one line at a time, left to right, top to bottom
  • For loops: check the condition before and after each iteration
  • Write values exactly as Python computes them (int vs float matters!)
  • If the code uses print(), record in the Output column at that step

Debugging Strategy

  • Read the error message carefully (especially the last line)
  • Locate the line number mentioned in the traceback
  • Add print() statements to check variable values at suspicious points
  • Test with simple, known inputs where you can calculate the expected output

Graded Tasks

Remember

Name the three types of errors and give one characteristic of each.

Understand

Classify each error: (a) primt("Hello") (b) int("abc") (c) Using n + 1 instead of n - 1 in a formula.

Apply

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

Apply

The following code should print the average of 3 numbers but has 3 bugs. Find and fix them:
total = 0; for i in range(3); n = input("Number: "); total += n; avg = total / 2; print(avg)

Analyze

Trace: s = ""; for i in range(1, 5): if i % 2 == 0: s += str(i); else: s += "*"; print(s)

Create

Write a deliberately buggy program (with 1 syntax error, 1 runtime error, and 1 logic error). Then provide the corrected version with explanations.

Self-Check Quiz

1. What type of error is a misspelled variable name like pritn instead of print?
Click to reveal answer
2. What type of error gives a wrong answer but doesn't crash?
Click to reveal answer
3. What columns should a trace table always include?
Click to reveal answer
4. How do you read a Python traceback?
Click to reveal answer
5. What error does int("hello") cause?
Click to reveal answer