Learn
B2.1.4 | DEBUGGING TECHNIQUES
01 | A WRONG ANSWER IS A CLUE
A program is supposed to total three scores: 4, 7 and 2. It prints 2. It does not crash, so there is no exception to explain the problem. Where should you start?
Debugging is the process of locating, understanding and correcting defects in a program. The aim is to use evidence to find the cause, rather than keep changing lines until one example seems to work.
This common SL/HL lesson develops four techniques from the specification: trace tables, print statements, breakpoint debugging and step-by-step execution. You will construct diagnostic code, follow state changes and test a justified correction.
02 | TESTING AND DEBUGGING HAVE DIFFERENT JOBS
Testing compares actual behaviour with an expected result. Debugging investigates why a mismatch occurs and corrects its cause. A test can reveal that the output is wrong without identifying the faulty statement.
For values [4, 7, 2], the expected sum is 13. Observing output 2 establishes a failure. Following each assignment then reveals that the total is repeatedly replaced rather than accumulated.
A useful workflow is: establish expected behaviour, reproduce the failure, inspect evidence, propose a cause, make a focused correction, then rerun appropriate tests.
03 | IDENTIFY THE KIND OF PROBLEM
| Kind | Example | Useful evidence |
|---|---|---|
| Syntax error | A missing colon prevents ordinary Python source being parsed. | The syntax message and indicated source location. |
| Runtime exception | A conversion or invalid operation raises during execution. | Traceback, inputs, current values and caller context. |
| Logic error | Valid statements produce the wrong sum. | Expected result, trace table, diagnostic prints or debugger state. |
The location where an exception is raised may be where a bad value is used, rather than where it first became wrong. Investigate the preceding state and the caller too.
Catching an exception can control a failure route, but is not automatically a correction for the underlying defect. A program that runs without an exception can still be wrong.
04 | MAKE THE FAILURE REPRODUCIBLE
Record the source version, input, expected result, actual result and relevant conditions. Reduce a large failing example to a smaller one that still demonstrates the same problem.
Use [4, 7, 2] rather than hundreds of values when investigating this sum. Keep a failing test available so you can check whether the change addresses the original issue.
If behaviour depends on a file, random data or previous program state, preserve or control those conditions. A fixed random seed can help reproduce one run but does not prove a solution works for every random case.
05 | READ THE REQUIREMENT BEFORE THE CODE
The required behaviour is “add every value and output the sum once”. That tells us what state should mean: after processing two values, total should be 4 + 7 = 11.
Without a clear expected result, a debugger can show you exactly what the program does while leaving you unsure whether it is right. A variable called total does not guarantee that the assigned value is a running total.
For each important variable, state its intended meaning at a particular point. This gives you something precise to compare with the observed state.
06 | THE BUGGY PROGRAM
values = [4, 7, 2]
total = 0
for number in values:
total = number
print(total)
A Python list groups the three numeric values. The for loop assigns each next value to number, then executes its indented body. Lists are explored in B2.2; here you only need to follow the values 4, 7 and 2 in order.
The loop body is total = number. It stores the current number, replacing whatever total previously held. The variable name suggests accumulation, but the actual operation does not perform it.
Predict every value before running the program. The first iteration appears correct, which makes a second, different value important for revealing the problem.
07 | CONSTRUCT A TRACE TABLE
| Point | number | Actual total | Expected running total |
|---|---|---|---|
| Initialisation | Not set | 0 | 0 |
| After first body | 4 | 4 | 4 |
| After second body | 7 | 7 | 11 |
| After third body | 2 | 2 | 13 |
| Final output | 2 | 2 | 13 |
The first incorrect state is after the second loop body. That is a better debugging clue than simply observing the final wrong output. The first iteration matches because starting from zero hides the difference between assignment and accumulation.
A trace table is a manual record of execution. It requires accurate following of the program’s actual statements, not writing the values you wish it would produce. Keep expected values in a clearly separate column.
08 | TRACE THE RIGHT-HAND SIDE FIRST
total = total + number
The correction reads the old total, adds the current number and stores the new result. On the second iteration this means 4 + 7 = 11. It preserves earlier contributions rather than overwriting them.
Now the sequence of total values is 0, 4, 11, 13. The final output is 13, and number remains 2 after the loop. A final loop variable and a final total are different pieces of state.
Do not “fix” the program by printing 13 directly. That only hardcodes the observed example and does not implement a sum for other inputs.
09 | PRINT DIAGNOSTICS AT A USEFUL LOCATION
values = [4, 7, 2]
total = 0
for number in values:
print("Before update:", "number =", number, "total =", total)
total = number
print("After update:", "number =", number, "total =", total)
print("Final total:", total)
Labels identify the variable and the time of observation. A bare print(total) inside a long program may reveal numbers without showing which operation produced them.
Printing immediately before and after a suspected assignment exposes its effect. Here the second before line shows total 4; the second after line shows 7, rather than the expected 11.
Construct diagnostics that answer a question, such as “what changed across this update?” Too much output can hide the relevant event.
10 | USE REPR AND TYPE WHEN APPEARANCES MISLEAD
raw = " 12 "
print("raw:", repr(raw), "type:", type(raw).__name__)
number = int(raw)
print("number:", repr(number), "type:", type(number).__name__)
repr exposes quotes and whitespace. The type display distinguishes numeric 12 from text "12". An input can look like a number when printed but still be a string.
For a substring bug, print the original text, its length, the found position and calculated slice bounds. For a comparison bug, print both operands and the condition result.
Diagnostic output should expose relevant state without publishing passwords or other sensitive data. Remove temporary prints or replace them with appropriate logging before sharing a finished application.
11 | BREAKPOINTS: PAUSE BEFORE A STATEMENT
A breakpoint tells a debugger where to pause execution. In typical line debugging, it pauses before executing the statement on that line. You can inspect the current state instead of adding many print calls.
Place a breakpoint on the update inside the loop. On its first hit, number is 4 and total is 0 because the update has not run. On its second hit, number is 7 and total is 4. Step once to see whether the result becomes 7 or 11.
A breakpoint does not change the algorithm or repair a defect. It gives you a controlled observation point. Debugger behaviour can vary with language and source mapping; interpret the displayed current statement carefully.
12 | WHAT TO INSPECT WHILE PAUSED
| Debugger view / action | What it helps you find |
|---|---|
| Variables | Current values in the selected scope. |
| Watch expression | A chosen expression, such as total + number, evaluated at pauses. |
| Call stack | Which calls led here and which frame you are inspecting. |
| Continue | Resume until another breakpoint, an exception pause, or completion. |
| Step over | Execute the current statement without entering its called function bodies. |
| Step into | Enter a callable’s implementation when supported and available. |
| Step out | Resume the current function until it returns, unless another stop occurs. |
A watch expression does not update total merely because total + number displays 11. It predicts/evaluates that expression. Avoid diagnostic expressions with side effects, such as calls that change stored data.
The selected stack frame matters: two functions can have different local variables with the same name. Inspect the scope in which the suspicious operation runs.
13 | SINGLE-STEP THROUGH A SMALL SECTION
Step-by-step execution advances through a program in manageable actions. Predict the next value, execute the statement, then compare the observed state with your prediction.
In the total example, stepping across the update reveals the incorrect assignment. In a substring example, stepping across the slice can reveal an exclusive-stop error. In a function call, step into is useful when the problem may be inside the function; step over is useful when its implementation is already understood.
Use a breakpoint to reach the relevant area, then step through a few statements. Stepping through an entire large program from its first line is often unnecessary.
14 | PYTHON DEBUGGING IN YOUR EDITOR
In VS Code, open the Python file and use an available Python debugging configuration. Set a line breakpoint in the editor gutter, start the debugger and select the current file if the editor asks what to debug. Inspect Variables and use Continue or the step controls.
The ordinary Run action may simply execute the program without attaching the debugger. Choose the debugging action when you want breakpoints to stop it. Exact menus and shortcuts depend on the editor, installed extensions and operating system.
In IDLE, the Debugger option in the Shell can enable its debugger before running a module. The underlying ideas are the same: pause, inspect and advance. Use the controls presented by your installation rather than assuming every IDE has identical buttons.
15 | INTERACTIVE: FIND THE FIRST WRONG UPDATE
This bounded debugger demonstrates the buggy and corrected sum programs. Each highlighted line is the next line to execute, and the state shows values before it. Step executes that line and moves to the next pause. A completed program has no highlighted next line.
Set a breakpoint on line 4, then Continue. You will pause before the update. Continue again to reach its next execution. Compare total before and after the second update in both versions. These states were recorded from actual Python runs; this is not an arbitrary-code editor.
| values | number | total |
|---|
16 | CHECK YOUR BREAKPOINT PREDICTIONS
| Pause before line 4 | Buggy total | Corrected total | number |
|---|---|---|---|
| First hit | 0 | 0 | 4 |
| Second hit | 4 | 4 | 7 |
| Third hit | 7 | 11 | 2 |
At the second hit both versions still have total 4. The divergence occurs when that second update executes: the buggy version stores 7, while the corrected version stores 11.
At completion, the outputs are 2 and 13 respectively. A breakpoint is before the current statement, so do not report its future assignment as already completed.
17 | CONDITIONAL BREAKPOINTS AND TARGETED OBSERVATION
When a loop runs many times, a conditional breakpoint can pause only when an expression is true, such as number == 7 in this example. Some debuggers also provide hit counts or logpoints. These are extensions to the core pause-and-inspect idea.
Choose conditions that expose the suspected failure. A condition total != expected is useful only when expected is correctly defined and available at that point. An incorrect diagnostic assumption can mislead you too.
The page’s simulator offers ordinary line breakpoints only. In an IDE, check the supported condition syntax and ensure observation does not alter the state you are investigating.
18 | A SUBSTRING BUG: THE STOP IS EXCLUSIVE
text = "ROBOTICS"
start = 2
length = 3
stop = length # wrong: length is not the stopping index
part = text[start:stop]
print(repr(part)) # 'B'
The required result is BOT. Print start, length and stop or inspect them at a breakpoint before the slice. They are 2, 3 and 3, so the slice includes only index 2.
The correction is stop = start + length, giving stop 5 and part BOT. An out-of-range slice might still run safely, so a lack of exceptions is not evidence of correct extraction.
Test start 0 as well as a nonzero start. The faulty formula can appear correct at start 0, which is why a varied test matters.
19 | A BRANCH BUG: CHECK EQUALITY AT THE LIMIT
age = 12
if age > 12: # wrong if the rule permits ages 12 and above
print("Allowed")
else:
print("Not yet")
Trace the condition using the actual value: 12 > 12 is false. The program follows else and displays Not yet. If the rule is at least 12, the correct operator is >=.
Test 11, 12 and 13. The surrounding cases can pass even when equality is wrong. A breakpoint before the decision and a watch on the condition expose why the unexpected branch is selected.
Correct the comparison only after confirming the requirement. Debugging must align behaviour with the intended rule, not merely make one chosen user happy.
20 | RUNTIME FAILURES: FOLLOW THE VALUE BACK
def points_per_person(total, people):
return total / people
print(points_per_person(12, 0))
The division raises ZeroDivisionError. The failing line shows where zero is used, but the cause may be in the caller’s data or an earlier count. Inspect the call stack and the local people value, then investigate where it came from.
A guard for a valid positive count may be appropriate, but first define what zero means in the problem. Do not silently substitute 1 and claim that the ratio is correct.
Use a controlled failure, meaningful validation or an appropriate handler according to the requirement. These responses do not replace correcting a broken count calculation.
21 | CHANGE ONE CAUSE, THEN TEST AGAIN
Form a hypothesis: “total is overwritten each iteration”. The trace supports it because total equals the most recent number after each assignment. Change that operation to accumulation and rerun the original failing test.
Then check different cases: [5] gives 5; [] gives 0 for this sum algorithm; [0, 0] gives 0; [3, −2] gives 1. These cases exercise one iteration, zero iterations, zeros and negative contributions.
Retest relevant previously working behaviour after the change. This is regression testing: the aim is to detect unintended effects of a correction, not to claim that a handful of tests proves every possible program correct.
22 | CONSTRUCT A DEBUGGING RECORD
| Record field | Worked entry |
|---|---|
| Requirement | Sum all supplied numbers and print the sum once. |
| Failure | [4,7,2] expected13, actual2. |
| Evidence | After the second update total is7, expected11. |
| Hypothesis | Assignment overwrites the accumulated value. |
| Correction | Use total = total + number. |
| Retest | Original case13; empty0; single5; mixed signs1. |
Keep the evidence and the correction connected. A clear record helps another programmer reproduce the issue and understand why the change addresses it.
Diagnostic code is temporary unless deliberately retained as suitable logging or tests. Remove noisy prints and confirm that final user output still matches the specification.
23 | YOUR TASK: REPAIR A QUALIFYING COUNT
The following function should count how many values are greater than 5, but it resets count inside the loop. Construct a trace table, add labelled diagnostic prints, identify a useful breakpoint and correct the program. Use [4, 8, 9] as the first failing test.
def count_high(values):
count = 0
for value in values:
count = 0 # wrong position: loses previous counts
if value > 5:
count = count + 1
return count
print(count_high([4, 8, 9]))
Reveal the diagnosis and correction
The result is 1, but should be 2. At the start of the third iteration count is reset from 1 to 0, losing the previous qualifying value. Keep count = 0 only before the loop. A breakpoint on the reset or prints immediately before and after it reveal the lost state.
def count_high(values):
count = 0
for value in values:
if value > 5:
count = count + 1
return count
print(count_high([4, 8, 9])) # 2
Retest an empty list (0), [5] (0), [6] (1) and [6, 7] (2). These distinguish the strict threshold from its boundary and reveal whether earlier counts persist.
24 | CHOOSE A TECHNIQUE FOR A REASON
| Technique | Good use | Limitation |
|---|---|---|
| Trace table | Small algorithms where you need to see each state and decision. | Manual mistakes and large traces can be difficult to manage. |
| Print statements | Targeted before/after evidence and values in a running program. | Noise and retained diagnostics can obscure intended output. |
| Breakpoint debugging | Pause near the problem and inspect state and scope. | Needs a suitable debugging setup; pauses can affect timing. |
| Step-by-step execution | Find the first unexpected change and follow calls. | Stepping every line of a large program can be slow. |
Combine techniques: use a test to reproduce the mismatch, a breakpoint to reach the suspected region, steps or prints to inspect the change, and a trace or record to explain the correction.
25 | COMMON MISTAKES
Do not record values after a highlighted statement if the debugger is paused before it. Do not confuse expected state with actual state in a trace. Do not assume the last printed wrong value identifies the first faulty operation.
Avoid random edits, hardcoded expected answers and blanket handlers that conceal evidence. Fix the cause, then test the original failure and relevant alternative paths.
For construct and use, produce and apply the technique: a completed trace, useful diagnostic statements, a stated breakpoint with inspected values or a documented step sequence. Merely listing the technique names is insufficient.
26 | READY TO DEBUG INDEPENDENTLY
Can you reproduce a failure, identify the first incorrect state, choose a suitable observation technique and explain why your correction addresses the cause? Can you separate a test result from the debugging evidence that explains it?
Use the activity, questions and flashcards to check these skills. The next section develops data structures, where the same debugging habits help you follow collections and their changes.