B2.1.4 Finding and fixing bugs
SL + HLCommand terms: Construct, Use1. The debugging cycle
Debugging is a process, not guesswork. Step through how a ShelfWise developer finds a bug where the total of all fines always comes out as 0.0.
2. Debugger simulator: breakpoints and step-by-step execution
Each program has a bug. Click a line number to set a breakpoint (a red dot). Run stops before a breakpoint line; Step runs one line; Continue runs to the next breakpoint. The highlighted line is the next line to run. The trace table fills in as the program runs.
Trace table (recorded automatically)
Found it?
3. Print-statement debugging
ShelfWise uses a simple 30-day month: a book borrowed on day 25 for 14 days should be due on day 9. The program says 8. Tick where to insert debug print() lines (shown in green), run, and read the clues.
Due: 24 then Due: 9.4. Construct a trace table
Complete the trace table by hand, as you would in an exam. Leave a cell empty if the variable does not change in that row. Then check.
5. Flip-card deck
Click to flip. Say the answer before you flip.
6. Pick the best technique
Which debugging technique fits the situation best? Streaks of 3+ score double.
7. 45-second speed round: syntax, runtime or logic error?
Classify each bug. Knowing the type tells you which technique to reach for.
shelfwise_buggy.py contains four bugs: one syntax error, one runtime error and two logic errors. Find and fix them with the techniques on this page, and keep a bug log: a professional habit, and evidence for your IA.Expected output once fixed
Suggested method
- Run it. Python reports the syntax error before anything runs: read the line number.
- Run again. The runtime error stops the program with a traceback: read the last line.
- Compare the output with the expected output. For each wrong value, set a breakpoint in the function (Thonny: Debug; VS Code: F9 then F5) or add a debug print, and step through.
- Fix, re-run, and remove any debug prints.
Bug log
Check my fixed code
Practical tasks
Three tasks for this topic, from Average to Moderate to Challenging. Start with the first and work up. Each coding task gives you a starter file with tests already written; you write the missing code.
- Open your PyCharm project (or New Project → pure Python, name it
ib_cs_tasks). - Right-click the project → New → Python File, using the file name shown on the task.
- Press Copy starter and paste it in, or press Download .py.
- Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
- Replace each
pass # your code herewith your own code. Do not change the code below# ---- tests ----. - Run the file and compare your output with Expected output. A crash or an
AssertionErrormeans something is not right yet. - Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
- Written parts: answer in your notebook first, then check the model answer.
Task 1: Find and fix the average bug
This function should return the average of a list, but it gives wrong answers. Add print statements inside the loop to find the bug, fix it, and remove the prints.
def average(nums):
total = 0
for i in range(1, len(nums)):
total += nums[i]
return total / len(nums)Starter file (write your code where it says pass # your code here):
def average(nums):
pass # your code here
# ---- tests ----
print(average([4, 8, 6]))
print(average([10]))
print(average([1, 2, 3, 4]))
Expected output when your code is correct:
6.0 10.0 2.5
Hint
i and total on each pass. Which index never appears?Model solution
The loop started at index 1, so the first number was never added (an off-by-one error). Printing i and total on each pass shows that index 0 is skipped.
def average(nums):
total = 0
for i in range(len(nums)):
total += nums[i]
return total / len(nums)
# ---- tests ----
print(average([4, 8, 6]))
print(average([10]))
print(average([1, 2, 3, 4]))
Task 2: Trace table, then test
Complete a trace table (columns: n, steps, output) for collatz_steps(6) by hand, then run the code to check it. Then write three assert tests, including the edge case n = 1.
Starter file (write your code where it says pass # your code here):
def collatz_steps(n):
pass # your code here
# ---- tests ----
print(collatz_steps(6))
assert collatz_steps(1) == 0
assert collatz_steps(2) == 1
assert collatz_steps(7) == 16
print("all asserts passed")
Expected output when your code is correct:
8 all asserts passed
Hint
Model solution
Trace for 6: 6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1, so steps = 8.
def collatz_steps(n):
steps = 0
while n != 1:
if n % 2 == 0:
n = n // 2
else:
n = 3 * n + 1
steps += 1
return steps
# ---- tests ----
print(collatz_steps(6))
assert collatz_steps(1) == 0
assert collatz_steps(2) == 1
assert collatz_steps(7) == 16
print("all asserts passed")
Task 3: Two bugs, caught by tests
This function should return the second-largest different value in a list, or None if there is none. It has two bugs. Write assert tests that expose both, then fix them.
def second_largest(nums):
first = second = 0
for n in nums:
if n > first:
first = n
elif n > second:
second = n
return secondStarter file (write your code where it says pass # your code here):
def second_largest(nums):
pass # your code here
# ---- tests ----
assert second_largest([3, 9, 5]) == 5 # bug 1: old first was thrown away
assert second_largest([-4, -1, -7]) == -4 # bug 2: starting at 0 fails for negatives
assert second_largest([5, 5, 5]) is None
assert second_largest([8]) is None
assert second_largest([2, 8, 8, 6]) == 6
print("all asserts passed")
Expected output when your code is correct:
all asserts passed
Hint
Model solution
Bug 1: when a new largest value is found, the old largest should become the second largest, but the original code discards it (try [3, 9, 5]). Bug 2: starting at 0 means negative lists give 0 (try [-4, -1, -7]). Duplicates of the largest value also need care.
def second_largest(nums):
first = second = None
for n in nums:
if first is None or n > first:
if first is not None:
second = first
first = n
elif n != first and (second is None or n > second):
second = n
return second
# ---- tests ----
assert second_largest([3, 9, 5]) == 5 # bug 1: old first was thrown away
assert second_largest([-4, -1, -7]) == -4 # bug 2: starting at 0 fails for negatives
assert second_largest([5, 5, 5]) is None
assert second_largest([8]) is None
assert second_largest([2, 8, 8, 6]) == 6
print("all asserts passed")
Learning objectives
By the end of this page you should be able to:
- Distinguish between syntax, runtime and logic errors.
- Construct trace tables to find errors by hand.
- Use breakpoint debugging, print statements and step-by-step execution to locate a bug.
- Apply a systematic debugging process: reproduce, locate, inspect, hypothesise, fix and retest.
Three kinds of error
| Type | When it shows | Example | How you find it |
|---|---|---|---|
| Syntax error | Before the program runs | if copies > 0 (missing colon) | The interpreter/compiler reports the line |
| Runtime error | While it runs: the program crashes | "Loans: " + 2 (TypeError) | Read the traceback; handle with try/except (B2.1.3) |
| Logic error | Never reported: the output is just wrong | total = 0 inside the loop | Test data plus the techniques below |
Debugging techniques
| Technique | How it works | Strengths | Limitations |
|---|---|---|---|
| Trace table | A table with a column per variable (and output); record each change as you execute the code by hand | No computer needed; makes you think through every step; standard in exams | Slow for long programs or many loop passes |
| Print statements | Temporary print() lines that show variable values or which branch ran | Works in any language and environment, even on a server log | Must edit the code; output can be noisy; must remember to remove them |
| Breakpoint | A marker in the IDE: the program runs normally, then pauses before that line so you can inspect variables | No code changes; jump straight to the suspicious part | Needs a debugger/IDE; less useful for timing problems |
| Step-by-step execution | Run one line at a time (step over, step into a function, step out) while watching variables | Shows the exact flow of control: which branch, how many loop passes | Tedious for long loops: combine with breakpoints |
A sensible process
- Reproduce the bug with known test data and an expected result.
- Locate it: narrow down where the values first go wrong (breakpoints or prints).
- Inspect: step through and watch the variables.
- Hypothesise the cause, then fix one thing at a time.
- Retest with the same data and with normal, boundary and abnormal data.
Debug prints that help
for days in days_held:
late = days - LOAN_DAYS
print("DEBUG days:", days, "late:", late, "total:", total) # label every value
...
Label values, print just before and after the suspicious line, and delete the prints (or switch them off) when you are done. In Java the same technique is System.out.println("DEBUG total=" + total);, and Java IDEs (BlueJ, IntelliJ, Eclipse) offer the same breakpoints and stepping.
Use the 中文 button at the top to show or hide the Chinese terms.
| Term | 中文 | Meaning |
|---|
Choose an answer. You get instant feedback.
Score: 0 /
Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.
1. Describe how a breakpoint is used when debugging a program. [2]
2. Outline one advantage and one disadvantage of using print statements for debugging. [2]
3. Construct a trace table for the code and state the output. [4]
x = 1
total = 0
while x < 4:
total = total + x * 2
x = x + 1
print(total)
12 [1].4. A program produces incorrect output but no error message. Identify the type of error, and describe how step-by-step execution could help find it. [3]
5. Distinguish between a syntax error, a runtime error and a logic error, giving an example of each. [3]
6. This code should print Average: 4.0 but prints Average: 12.0. Identify the error and explain how a trace table would reveal it. [4]
loans = [4, 2, 6]
total = 0
count = 0
for n in loans:
total = total + n
count = count + 1
print("Average:", total / count)
count = count + 1 is not indented, so it is outside the loop [1] and runs only once, giving 12 / 1 [1]. A trace table would show total changing on every pass (4, 6, 12) [1] while count stays 0 throughout the loop and becomes 1 only afterwards, revealing the misplaced line [1].