Skip to content
ComputerCS
Start learning

Python Programming · Lesson 2.10.1.2–2.10.1.3

Debugging & Tracebacks

Read tracebacks bottom-up, interrogate your program with print-debugging, and recognise the classic bug patterns on sight.

01

Learning objectives

  • Read a traceback from the bottom line upward and name the error type and message.
  • Use temporary print() statements to localise a bug, then remove them.
  • Apply the rubber-duck method: explain the code line by line aloud.
  • Recognise and fix off-by-one loop errors and integer-division surprises.
  • Follow a systematic routine: reproduce, isolate with one change, fix, re-test.
02

Lesson notes

A traceback is Python's accident report, and it is read bottom-up. The last line names the error type and message — start there. The lines above walk back through the calls, each showing a file and a line number. Visit the reported line of your code, but remember the true mistake is often a line or two earlier: the crash site is where the damage shows, not always where it was caused.

print-debugging is the everyday tool of professionals, whatever the jokes say. Place temporary print() statements at checkpoints — before the loop, inside it, after it — printing the values you assume. Run, compare what is with what you assumed, and the gap locates the bug. Then halve the distance: put a print between the last good and the first bad checkpoint. Remove the prints when you are done.

Add the method: reproduce the bug every single time, change one thing, re-test, repeat. Random edits that seem to fix it leave hidden versions of the same bug behind. The rubber-duck technique complements this: explain your code line by line aloud to a duck, or a patient sibling — narrating forces you to say what each line actually does, and the mismatch with your intention usually jumps out mid-sentence.

Learn the repeat offenders. Off-by-one: range(len(nums) + 1), or nums[i + 1] inside a loop that already runs to the end — the classic IndexError. Integer division // written where true division / was meant — silently truncated results. Assignment = where comparison == was meant. Mutating a list while looping over it, which skips elements. Each has a signature smell: off-by-one crashes at the boundary, and // gives suspiciously round answers.

Board tip: the practical exam hands you buggy programs worth marks for fixes, not rewrites. Protocol: read the traceback or the wrong output, state the expectation aloud — this should print 360 — trace the relevant lines by hand, apply the smallest possible fix, then re-run with the original data and one new test case. Rewriting working-looking code from scratch usually loses marks and imports new bugs.

03

Worked code examples

print-debugging in action

The checkpoints confirm the loop total (400) and the subtraction (360). Once trusted, the DEBUG lines are deleted — they were scaffolding.

def total_price(prices, discount):
    total = 0
    for p in prices:
        total = total + p
    print("DEBUG total before discount:", total)
    final = total - discount
    print("DEBUG final:", final)
    return final

print(total_price([100, 250, 50], 40))
Output
DEBUG total before discount: 400
DEBUG final: 360
360

The off-by-one pattern, fixed

With i reaching 2, nums[i + 1] would ask for index 3 of a 3-element list. Looping exactly over valid indexes keeps every access inside.

nums = [10, 20, 30]
# Buggy:  for i in range(len(nums)): print(nums[i + 1])  -> IndexError
for i in range(len(nums)):
    print(nums[i])
Output
10
20
30

A logical bug you can only catch by testing

// silently truncates the fraction — the program runs but reports 85. Testing against the hand-computed 85.67 exposes the wrong operator.

marks = [80, 85, 90]
average = sum(marks) // len(marks)
print(average)
average = sum(marks) / len(marks)
print(average)
Output
85
85.0
04

Key terminology

traceback

Python's report of where an exception happened: the calls taken and the final error line.

print-debugging

Inserting temporary print() statements to inspect values and narrow down a bug.

rubber-duck debugging

Explaining your code aloud, line by line, to expose the gap between intention and reality.

off-by-one error

A loop or index that runs one step too far or stops one step short.

reproduce

Re-creating a bug reliably every time — step one of any serious debugging session.

05

Common misconceptions

Common mistake

The line number in a traceback always points at the buggy line.

Correct understanding

It points where the error surfaced; the cause may be earlier — for example a wrong value computed long before the crashing line used it.

Common mistake

Real programmers only use debuggers; print-debugging is amateur.

Correct understanding

Temporary prints are a standard, respected technique — quick, universal and often the fastest way to localise a bug.

Common mistake

If the fix works once, debugging is done.

Correct understanding

Re-run the original failing case plus a fresh test; untested fixes regularly break a second path or reintroduce the bug.

06

Check your understanding

1. Which part of a traceback do you read first?

2. for i in range(len(nums) + 1): print(nums[i]) typically raises —

3. Which debugging routine is most likely to find the bug without creating new ones?

NERDLYY · FEEDBACK

Help shape Nerdlyy

Your feedback goes directly to the team. We read every submission.

No reply needed — you can send feedback without sharing contact details.