Home › Theme B › B2 › B2.1 › B2.1.4

B2.1.4 Finding and fixing bugs

SL + HLCommand terms: Construct, Use

1. 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.

Bug hunt:
Ready
Variables
Output

Trace table (recorded automatically)

Found it?

The bug is on line

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.

Output
Press Run.
Expected output: Due: 24 then Due: 9.
The bug is on line and the fix is

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.

Round 0/10Score 0Streak 0Best 0
Press start!

7. 45-second speed round: syntax, runtime or logic error?

Classify each bug. Knowing the type tells you which technique to reach for.

Time 45sScore 0Streak 0Best 0
Press start!
ShelfWise · Sprint 1, task 4. A teammate merged a broken version of ShelfWise. 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

Loans today: 2 Code: DUN-F Fine for 20 days: 3.0 Fine for 10 days: 0.0

Suggested method

  1. Run it. Python reports the syntax error before anything runs: read the line number.
  2. Run again. The runtime error stops the program with a traceback: read the last line.
  3. 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.
  4. Fix, re-run, and remove any debug prints.

Bug log

Check my fixed code

    Sprint 1 complete. Next sprint (B2.2): ShelfWise stores many books in lists, uses a stack for undo and a queue for the reservation waitlist.

    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.

    Set up in PyCharm
    1. Open your PyCharm project (or New Project → pure Python, name it ib_cs_tasks).
    2. Right-click the project → New → Python File, using the file name shown on the task.
    3. Press Copy starter and paste it in, or press Download .py.
    4. Right-click in the editor → Run (Windows Shift+F10, Mac Ctrl+R).
    How the tasks work
    1. Replace each pass # your code here with your own code. Do not change the code below # ---- tests ----.
    2. Run the file and compare your output with Expected output. A crash or an AssertionError means something is not right yet.
    3. Stuck for more than 10 minutes? Open the Hint. Open the Model solution only after a real attempt, then compare it with yours.
    4. Written parts: answer in your notebook first, then check the model answer.
    Average

    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):

    File: b2_1_4_average.py
    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
    Print 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.

    File: b2_1_4_average_solution.py
    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]))
    
    Moderate

    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):

    File: b2_1_4_moderate.py
    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
    A row of the trace table each time n changes.
    Model solution

    Trace for 6: 6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1, so steps = 8.

    File: b2_1_4_moderate_solution.py
    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")
    
    Challenging

    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 second

    Starter file (write your code where it says pass # your code here):

    File: b2_1_4_challenging.py
    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
    Test with the largest value in the middle, with all negatives, and with duplicates.
    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.

    File: b2_1_4_challenging_solution.py
    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:

    1. Distinguish between syntax, runtime and logic errors.
    2. Construct trace tables to find errors by hand.
    3. Use breakpoint debugging, print statements and step-by-step execution to locate a bug.
    4. Apply a systematic debugging process: reproduce, locate, inspect, hypothesise, fix and retest.

    Three kinds of error

    TypeWhen it showsExampleHow you find it
    Syntax errorBefore the program runsif copies > 0 (missing colon)The interpreter/compiler reports the line
    Runtime errorWhile it runs: the program crashes"Loans: " + 2 (TypeError)Read the traceback; handle with try/except (B2.1.3)
    Logic errorNever reported: the output is just wrongtotal = 0 inside the loopTest data plus the techniques below

    Debugging techniques

    TechniqueHow it worksStrengthsLimitations
    Trace tableA table with a column per variable (and output); record each change as you execute the code by handNo computer needed; makes you think through every step; standard in examsSlow for long programs or many loop passes
    Print statementsTemporary print() lines that show variable values or which branch ranWorks in any language and environment, even on a server logMust edit the code; output can be noisy; must remember to remove them
    BreakpointA marker in the IDE: the program runs normally, then pauses before that line so you can inspect variablesNo code changes; jump straight to the suspicious partNeeds a debugger/IDE; less useful for timing problems
    Step-by-step executionRun one line at a time (step over, step into a function, step out) while watching variablesShows the exact flow of control: which branch, how many loop passesTedious for long loops: combine with breakpoints

    A sensible process

    1. Reproduce the bug with known test data and an expected result.
    2. Locate it: narrow down where the values first go wrong (breakpoints or prints).
    3. Inspect: step through and watch the variables.
    4. Hypothesise the cause, then fix one thing at a time.
    5. 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]

    A breakpoint is set on a chosen line, and the program runs normally until it reaches that line, where execution pauses [1]; the programmer can then inspect the current values of variables / step through the following lines to see where values go wrong [1].

    2. Outline one advantage and one disadvantage of using print statements for debugging. [2]

    Advantage: works in any language or environment without a debugger / quick to add / shows values over many iterations [1]. Disadvantage: the code must be edited and the prints removed afterwards / output can become cluttered / the program must be re-run each time [1].

    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)
    Columns x, total, x < 4, output [1]. Rows: x 1, total 0 / True, total 2, x 2 / True, total 6, x 3 / True, total 12, x 4 [1 for first two passes, 1 for the third]; condition False, output 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]

    A logic error [1]. Executing one line at a time while watching the variables [1] shows the exact line where a variable takes an unexpected value / the wrong branch is taken, locating the faulty statement [1].

    5. Distinguish between a syntax error, a runtime error and a logic error, giving an example of each. [3]

    Syntax error: breaks the language rules so the code cannot run, e.g. a missing colon [1]; runtime error: occurs during execution and stops the program, e.g. division by zero [1]; logic error: the program runs but gives wrong results, e.g. using > instead of >= [1].

    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].