Debugging

Topic 1 of 4 in Tools and projects8 min readBeginnerFree course

Overview

Every programmer writes bugs — what separates experienced developers is how quickly they find them. Debugging isn’t guessing and changing things until it works; it’s a calm, repeatable process. This lesson gives you that process and the tools that support it.

A debugging workflow in five steps. 1, Reproduce — find the smallest input that fails. 2, Read the traceback — bottom line first: type and message. 3, Inspect — print(f”{x=}“) or breakpoint(). 4, Hypothesise — what should happen versus what does. 5, Fix and test — add a test so it never returns. breakpoint() opens pdb, where p total prints 42, n runs the next line, s steps into a call, l lists the code, c continues and q quits. Editors such as VS Code and PyCharm offer the same with clickable breakpoints and a variables panel.

1. Reproduce

You can’t fix what you can’t see. Find a way to make the bug happen every time, then shrink it: the smallest input, the fewest steps. A bug that appears with a 10,000-line file often appears with three lines too — and three lines are much easier to reason about.

2. Read the error

If there’s a traceback, read it from the bottom (Your first program): the exception type, the message, then the file and line. Recent Python versions point at the exact expression with ^ marks and often suggest a fix. Also check the lines above the failing one — the bad value usually came from somewhere earlier.

Many bugs produce no error at all, just wrong output. Then you need to look inside.

3. Inspect: print debugging

The simplest tool is still extremely effective. Print the values you’re unsure about — with the = specifier, which shows the name as well:

Python
def average(numbers):
    total = 0
    for n in numbers:
        total += n
        count = len(numbers) - 1
    print(f"{total=}, {count=}")      # total=12, count=2
    return total / count

Tips:

  • Print types too when something’s odd: print(f"{x=!r} {type(x)=}") — '5' vs 5 explains many bugs.
  • Print at the start and end of a function to see what goes in and comes out.
  • Remove the prints when you’re done (or turn them into logging, below).

Stepping through code: breakpoint() and pdb

Print debugging means re-running the program for each new question. A debugger pauses the program so you can ask as many questions as you like. Add breakpoint() where you want to stop:

Python
def apply_discount(prices, percent):
    result = prices
    breakpoint()
    for i in range(len(result)):
        ...

Run the program normally. It pauses and opens pdb, Python’s built-in debugger:

Text
> /home/asha/shop.py(3)apply_discount()
-> breakpoint()
(Pdb) p result is prices
True
(Pdb) n
> /home/asha/shop.py(4)apply_discount()
-> for i in range(len(result)):
(Pdb)

The -> line shows where the program is paused (since Python 3.13, that’s the breakpoint() line itself); each n moves one line on.

Command Does
p expr print an expression
pp expr pretty-print (nice for big dicts)
n next — run the current line
s step into a function call
c continue until the next breakpoint
l / ll list the code around here / the whole function
w where — show the call stack
q quit

p result is prices returning True reveals the bug in the exercise straight away: both names point to one list.

Editor debuggers

VS Code and PyCharm give you the same power with a mouse: click in the margin to set a breakpoint (a red dot), press F5 / Debug, and the program stops there. A side panel shows every variable, and buttons step over, into and out of lines. Many developers use this every day — it’s well worth ten minutes to learn.

4. Hypothesise

Once you can see the values, compare what should happen with what does. State a specific theory — “count is one too small because of the - 1” — and test it, rather than changing several things at once. If the theory’s wrong, you’ve still learned something.

Rubber duck debugging really works: explain the code, line by line, out loud to someone (or something). You’ll often hear yourself say the bug.

5. Fix and prevent

Make the smallest change that fixes the cause, not just the symptom. Then write a test that would have caught the bug (Testing with pytest), so it can never silently return.

Common bug patterns

Symptom Usual suspect
A list changes “by itself” two names for one list (b = a), or a mutable default argument
Off by one range(len(x) - 1), < vs <=, slices stopping before the stop index
None where a value was expected a function that prints instead of returning, or x = x.sort()
'5' + 1 errors or '55' instead of 10 input() text not converted with int()
Loop runs zero times the condition was false from the start, or the collection was empty
Works once, not twice an exhausted iterator or generator
Comparisons fail on floats 0.1 + 0.2 != 0.3 — use math.isclose or round

logging: prints you can keep

For messages you’d like to keep in your program — progress, warnings, details for diagnosing problems later — use the logging module instead of print:

Python
import logging

logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
log = logging.getLogger(__name__)

log.debug("Parsed %d rows", len(rows))     # hidden at INFO level
log.info("Saved report to %s", path)
log.warning("Price missing for %s", item)
log.error("Could not connect to the database")

Change one setting (level=logging.DEBUG) to see the detailed messages, or send everything to a file with filename="app.log" — without touching the rest of the code.

The process: reproduce → read → inspect → hypothesise → fix → test. Change one thing at a time, and trust what the values tell you over what you expect.

Exercise

Fix three bugs

The starter has three functions, each with one bug, and a test line under each that prints what it returns. Don’t guess: for each one, run it, add print(f"{variable=}") lines or a breakpoint() to watch the variables, find the cause, and fix it. When you’re done, the program should print True three times. Remove your debugging prints afterwards.

Python
def average(numbers):
    """Return the mean of numbers."""
    total = 0
    for n in numbers:
        total += n
        count = len(numbers) - 1
    return total / count


def apply_discount(prices, percent):
    """Return a new list with every price reduced by percent."""
    result = prices
    for i in range(len(result)):
        result[i] = round(result[i] * (1 - percent / 100), 2)
    return result


def word_lengths(text):
    """Return a dict mapping each word (lower case) to its length."""
    lengths = {}
    for word in text.split(" "):
        lengths[word.lower()] = len(word)
    return lengths


print(average([2, 4, 6]) == 4)
original = [10.0, 20.0]
print(apply_discount(original, 10) == [9.0, 18.0] and original == [10.0, 20.0])
print(word_lengths("Hello  world") == {"hello": 5, "world": 5})

Summary

  • Debug systematically: reproduce the bug, read the traceback, inspect values, form a hypothesis, fix, and add a test.
  • print(f"{x=}") is the fastest way to see a variable’s name and value.
  • breakpoint() pauses the program in pdb: p prints, n runs the next line, s steps in, c continues, q quits.
  • Editor debuggers (VS Code, PyCharm) do the same with clickable breakpoints and a variables panel.
  • Use the logging module instead of print for messages you want to keep, with levels like DEBUG, INFO and ERROR.