Lesson 14: Debugging — Tracebacks, Logging and pdb
Every programmer spends a large part of their time debugging, and the professionals are not the ones who write bug-free code — they are the ones who find bugs fast. The first skill is reading a traceback. When Python raises an unhandled exception, it prints the chain of function calls that led to the failure, with the most recent call at the bottom. The last line names the exception and its message; the lines above it show the file, line number and code for each step. Reading bottom-up — what failed, then where — will solve most bugs in seconds.
The second skill is replacing scattered print() calls with the logging module. Prints are hard to turn off, hard to filter, and they mix debugging noise with real output. Logging gives you levels — DEBUG, INFO, WARNING, ERROR — and a single switch to control how much detail you see. The example below configures logging once, then records what the program is doing at each level. In production you set the level to WARNING and the debug chatter disappears; when something breaks, you turn it back to DEBUG and the story reappears.
import logging
logging.basicConfig(level=logging.DEBUG,
format="%(levelname)s: %(message)s")
log = logging.getLogger(__name__)
def divide(a, b):
log.debug("dividing %s by %s", a, b)
if b == 0:
log.error("division by zero attempted")
raise ValueError("cannot divide by zero")
return a / b
print(divide(10, 2)) # 5.0
Stepping through with pdb
When a traceback and some logging are not enough, the debugger is the next tool. Python ships one in the standard library: pdb. You can start it by putting breakpoint() in your code — execution stops there and gives you an interactive prompt. From that prompt you can print variables (p name), step to the next line (n), step into a function call (s), continue running (c), or quit (q). Watching a variable change step by step is often the fastest way to understand a bug that no amount of staring at the code will reveal.
A practical debugging workflow ties these three tools together. First, read the traceback and reproduce the bug with the smallest possible input. Second, add logging around the suspicious area so you can see what the program actually did, not what you assumed it did. Third, if the cause is still unclear, set a breakpoint and step through the code, checking your assumptions one variable at a time. And when you find the bug, write a test that fails because of it before you fix it — that test is the subject of the next two lessons, and it is what stops the same bug from ever coming back.
Going further
Two debugging habits are worth more than any tool. The first is rubber-duck debugging: explaining the code aloud, line by line, to an inanimate object (or a patient friend). The act of saying what each line is supposed to do often reveals the line that does something else — the bug is usually in the gap between intention and code, and speech makes the intention explicit. The second is binary-search debugging: if a program worked yesterday and fails today, test the halfway point of your changes to find which half introduced the bug, and repeat. Both habits work without any software at all.
Python also has a built-in assert statement, which checks a condition and raises AssertionError if it is false. Assertions are for things that should never happen — internal invariants, not user errors. A good place for one is at the start of a function that assumes its input is sorted, or after a computation that must produce a positive number. Unlike tests, assertions live in the code itself and run every time, which makes them a living form of documentation: they state what the programmer believed to be true at that exact point.
A useful debugging exercise is to take a program that works and deliberately break it in a small way — change a < to a <=, or an index by one — and then find the bug using only the traceback and logging, without reading the change you made. It sounds artificial, but it trains the exact skill that real debugging requires: forming a hypothesis about what is wrong, testing it with evidence, and updating it when the evidence disagrees. Programmers who practise this way find real bugs faster, because they have rehearsed the process when the stakes were low and the answer was known.
Key Terms
- Traceback
- The report Python prints for an unhandled exception, listing the chain of calls with file names and line numbers.
- logging
- The standard-library module for recording messages at levels (DEBUG, INFO, WARNING, ERROR) with one central configuration.
- Log level
- The severity of a log message; the configured level decides which messages are shown and which are hidden.
- pdb
- Python's built-in interactive debugger, entered with breakpoint() or python -m pdb.
- breakpoint()
- A built-in that pauses execution and opens the debugger at that line.
- Step (n) / step into (s)
- Debugger commands: n runs the next line, s steps into a function call.
- Reproduce
- Triggering a bug reliably with the smallest possible input, the first step in fixing it.
Discussion Questions
- Why is reading a traceback bottom-up usually faster than reading it top-down?
- What is wrong with leaving print() debugging statements in a finished program? What does logging do better?
- When would you reach for pdb instead of adding more logging? What does stepping through code show you that logs cannot?
Practice Questions
- In a traceback, which line tells you what went wrong?
- With the level set to WARNING, which messages appear: DEBUG, INFO, WARNING, ERROR?
- What does
breakpoint()do when the program reaches it? - In pdb, what is the difference between
nands? - Why write a failing test before fixing a bug?
Show answers
- The last line, which names the exception type and its message. The lines above it show the chain of calls that led there.
- WARNING and ERROR only. The level is a threshold: messages at or above it are shown, quieter ones are hidden.
- It pauses execution and opens the pdb debugger prompt. From there you can inspect variables and step through the code.
- n steps over a function call; s steps into it. Use s when you want to watch what happens inside the called function.
- So the fix is proven and the bug can never silently return. The test fails because of the bug, then passes after the fix — and guards the code forever after.