Programming fundamentals · Beginner · 18 min
Step through Python code with breakpoint() and pdb
By Padding · Updated 18 Nov 2026
Python 3.15.2 · python:3.15-slim (Debian)
You will pause a Python script that prints the wrong average, step through it line by line with pdb, find and fix the bug without adding a single print, and inspect a crash after it happens.
On this page
When a program gives the wrong answer, the usual first move is to scatter print() calls through it, run it, read the output, move the prints and run it again. That works, but every guess costs an edit and a rerun, and the prints have to come out again afterwards.
A debugger lets you do the same investigation while the program is running. You pause it at a line you choose, look at any variable, run one line at a time and watch the values change. Python ships with one, called pdb, in the standard library. There is nothing to install and it needs no internet connection, so it works the same on a laptop, a server you reach over SSH, or Python in the Termux app on an Android phone.
In this tutorial you debug a small script that works out average daily mobile data use from a week of readings, the kind of number you might track to make a prepaid bundle last. It prints an average that is too low. You pause it with breakpoint(), step through the loop, start it under python3 -m pdb with a conditional breakpoint, move up and down the call stack, fix the bug, and then use pdb's post-mortem mode to inspect a crash after it has happened.
The examples use python3. On Windows outside WSL, type py instead.
Step 1 · Run the script and see the wrong answer
Make a folder for this tutorial and write the script. A reading of 0 means the phone recorded nothing that day, so those days should be left out of the average:
mkdir -p ~/pdb-demo
cd ~/pdb-demo
cat > data_use.py <<'PY'
"""Average daily mobile data use, skipping days with no reading."""
def average_usage(days):
total = 0
count = 0
for mb in days:
if mb > 0:
total += mb
count += 1
return total / count
def main():
usage = [120, 0, 80, 0, 100]
result = average_usage(usage)
print(f"Average use: {result:.1f} MB a day")
if __name__ == "__main__":
main()
PY
python3 data_use.pyWhat the script is meant to do:
average_usage(days)keeps a runningtotalof megabytes and acountof days with a reading, then divides one by the other.if mb > 0:is there to skip the days with no reading.main()passes in five days of readings and prints the result to one decimal place.if __name__ == "__main__":runsmain()only when you run the file directly, not when another file imports it. You use that in the last step.
Work out the right answer by hand before you trust the program: the real readings are 120, 80 and 100, which add up to 300, over 3 days. The average should be 100.0.
Check it worked
The script prints Average use: 60.0 MB a day. That is the bug you are going to find. Resist the urge to read the code for it; the point is to let the debugger show you.
Step 2 · Pause inside the loop with breakpoint()
breakpoint() is a built-in function. When Python reaches it, the program stops and hands control to pdb, with every variable as it is at that moment. Rewrite the script with a breakpoint() call as the first line inside the loop:
cat > data_use.py <<'PY'
"""Average daily mobile data use, skipping days with no reading."""
def average_usage(days):
total = 0
count = 0
for mb in days:
breakpoint()
if mb > 0:
total += mb
count += 1
return total / count
def main():
usage = [120, 0, 80, 0, 100]
result = average_usage(usage)
print(f"Average use: {result:.1f} MB a day")
if __name__ == "__main__":
main()
PYNow run it:
python3 data_use.pyThe program stops before printing anything and shows something like this:
> /home/you/pdb-demo/data_use.py(8)average_usage()
-> breakpoint()
(Pdb)The first line is the file, the line number in brackets and the function you are in. The -> line is the line pdb is on. (Pdb) is the prompt: pdb is waiting for a command. Type these four, pressing Enter after each:
l
p mb
p total, count
p daysl(list) shows the source around where you are, with line numbers and an arrow at the current line. Use it whenever you lose your place.p mb(print) evaluatesmband shows its value:120, the first reading.p total, countshows both counters as a pair:(0, 0), because no line in the loop has run yet.p daysshows the whole list the function received.
p takes any Python expression, so p total / 2 or p len(days) work too.
To leave, type q. Because the debugger was started by breakpoint() inside a running program, pdb asks Quit anyway? [y/n]. Type y and the program stops without finishing.
Check it worked
l printed lines 3 to 13 of the file with -> beside line 8, p mb printed 120, p total, count printed (0, 0) and p days printed [120, 0, 80, 0, 100].
Step 3 · Watch the counters change line by line
Run the script again. This time you move through the loop yourself, one line at a time, and check the counters as you go:
python3 data_use.pyAt the (Pdb) prompt, type:
n
n
n
p total, count
c
p mb
n
n
p total, countn(next) runs the current line and stops at the next one in the same function. After threencommands you have gone pastif mb > 0:andtotal += mb, and pdb shows-> count += 1, the line it is about to run.p total, countnow shows(120, 0): the reading has been added, andcountis about to go up.c(continue) lets the program run freely until it hits a breakpoint again. Becausebreakpoint()is inside the loop, that happens at the start of the next day.p mbshows0: this is a day with no reading.- Two more
ncommands. Watch which lines pdb shows. It goes fromif mb > 0:straight to-> count += 1, skippingtotal += mb, which is right. But it still lands oncount += 1. p total, countshows(120, 1), andcount += 1is about to run for a day with no reading.
That is the bug. count += 1 is not indented under the if, so it runs for every day, including the empty ones. The function divides 300 by 5 instead of 3, which gives 60.
When you are done, type c four times to let the remaining days run, or q then y to stop.
Check it worked
The second p total, count printed (120, 1) while mb was 0. You can say, from what you saw, which line runs when it should not. You have not added a single print().
Step 4 · Start the script under pdb with a conditional breakpoint
Stopping on every day of the loop gets slow with a year of readings instead of five. A better tool is a breakpoint with a condition: pdb only stops when the condition is true. You can also set breakpoints without editing the file at all, by starting the script under the debugger with python3 -m pdb.
First take the breakpoint() line out again, so the file is back to the original:
cat > data_use.py <<'PY'
"""Average daily mobile data use, skipping days with no reading."""
def average_usage(days):
total = 0
count = 0
for mb in days:
if mb > 0:
total += mb
count += 1
return total / count
def main():
usage = [120, 0, 80, 0, 100]
result = average_usage(usage)
print(f"Average use: {result:.1f} MB a day")
if __name__ == "__main__":
main()
PYIn this version, line 10 is count += 1 and line 16 is result = average_usage(usage). Start the script under pdb:
python3 -m pdb data_use.pypdb stops before the first line of the file, at the docstring on line 1. Type:
b 16
c
s
b 10, mb == 0
c
pp locals()b 16(break) sets breakpoint 1 on line 16. pdb confirms withBreakpoint 1 at ...data_use.py:16.cruns until that breakpoint, so you stop inmain()just before it callsaverage_usage.s(step) runs the current line but, unliken, follows it into any function it calls. pdb prints--Call--and you are now at the top ofaverage_usage. Useswhen you want to go inside a function,nwhen you trust it and want to step over it.b 10, mb == 0sets breakpoint 2 on line 10, but only for days wheremb == 0. The condition is any Python expression.cruns until the condition is true, which is the first empty day.pp locals()(pretty-print) shows every local variable in one go.locals()is a built-in that returns them as a dictionary, andpplays out long values more readably thanp.
Leave the session open for the next step, or type q to quit. A script started with python3 -m pdb quits straight away, with no confirmation.
Check it worked
pp locals() printed {'count': 1, 'days': [120, 0, 80, 0, 100], 'mb': 0, 'total': 120}. pdb stopped on day two, the first day with mb equal to 0, and you can see count is about to go up anyway.
Step 5 · Move up and down the call stack with w, u and d
When pdb stops inside a function, the function that called it is still waiting, paused at its own line. That chain of waiting functions is the call stack. pdb can show it and let you look at the variables in any of them.
If you quit in the last step, start again and get back to the empty day:
python3 -m pdb data_use.pyb 10, mb == 0
c
w
u
p usage
d
p mb
qw(where) prints the stack, oldest call at the top and the current frame at the bottom, marked with>. The first few entries are pdb's own code and the module level of your script. Near the bottom you seemain()waiting at line 16, thenaverage_usage()at line 10.u(up) moves one frame towards the caller. You are now looking atmain(). The program has not moved; only your view has.p usageworks here becauseusageis a variable inmain(). Inaverage_usagethe same list is calleddays.d(down) moves back toaverage_usage, andp mbshows0again.
w, u and d are most useful when a function gets a bad value and you need to see where it came from.
Check it worked
After w, the last two entries are main() at line 16 and average_usage() at line 10. After u, pdb showed -> result = average_usage(usage), and p usage printed [120, 0, 80, 0, 100].
Step 6 · Fix the bug and run it without the debugger
The fix is one indent: count += 1 belongs inside the if, so it only counts days with a reading. Rewrite the file with the fix:
cat > data_use.py <<'PY'
"""Average daily mobile data use, skipping days with no reading."""
def average_usage(days):
total = 0
count = 0
for mb in days:
if mb > 0:
total += mb
count += 1
return total / count
def main():
usage = [120, 0, 80, 0, 100]
result = average_usage(usage)
print(f"Average use: {result:.1f} MB a day")
if __name__ == "__main__":
main()
PY
python3 data_use.pyCheck it worked
The script prints Average use: 100.0 MB a day, the answer you worked out by hand in the first step. There are no print() calls or breakpoint() lines to clean up.
Step 7 · Inspect a crash after it happens
Some bugs end in a crash rather than a wrong number. A traceback tells you where it happened; pdb's post-mortem mode lets you look at the variables at that moment, as if you had set a breakpoint there in advance.
The fix has a new weakness. A week where the phone recorded nothing leaves count at 0, and dividing by zero crashes. Write a second script that imports the function and tries it:
cat > empty_week.py <<'PY'
from data_use import average_usage
print(average_usage([0, 0, 0, 0, 0, 0, 0]))
PY
python3 empty_week.py || echo "exit status $?"The traceback ends with ZeroDivisionError: division by zero and the shell prints exit status 1. Now run it under pdb:
python3 -m pdb -c continue empty_week.py-c continue gives pdb the continue command before it starts, so the script runs straight through to the crash. pdb prints the traceback, then Uncaught exception. Entering post mortem debugging, and stops on the line that failed, -> return total / count. Type:
p days
p total, count
qp days shows seven zeros and p total, count shows (0, 0): the function had nothing to divide. You can use l, w, u and d here too. If you type c instead of q, pdb restarts the script from the top; q leaves.
Decide what an empty week should mean and say so in the code. Here it returns 0.0, so the report shows zero use:
cat > data_use.py <<'PY'
"""Average daily mobile data use, skipping days with no reading."""
def average_usage(days):
total = 0
count = 0
for mb in days:
if mb > 0:
total += mb
count += 1
if count == 0:
return 0.0
return total / count
def main():
usage = [120, 0, 80, 0, 100]
result = average_usage(usage)
print(f"Average use: {result:.1f} MB a day")
if __name__ == "__main__":
main()
PY
python3 data_use.py
python3 empty_week.pyCheck it worked
In the pdb session, p total, count printed (0, 0) at the line that crashed. After the last change, data_use.py prints Average use: 100.0 MB a day and empty_week.py prints 0.0 instead of a traceback.
Step 8 · Use the same ideas in an editor, and clean up
Editor debuggers, such as the one in VS Code with its Python extension, and the debuggers in PyCharm and other IDEs, do what you have just done with buttons instead of typed commands. You click in the margin beside a line number to set a breakpoint, and you can right-click it to add a condition such as mb == 0. Continue is c, Step Over is n, Step Into is s, and Step Out runs to the end of the current function. A Variables panel shows what pp locals() showed, a Call Stack panel shows what w showed and lets you click a frame instead of typing u and d, and a Debug Console evaluates expressions like p. If you know pdb, any of them takes minutes to learn, and pdb is still there when all you have is a terminal on a remote server.
Two habits to keep:
- Never leave
breakpoint()in code you share or deploy. A program that pauses waiting for input it will never get looks like it has hung. Search for it before you commit:grep -rn "breakpoint()" . - If one slips through, setting the environment variable
PYTHONBREAKPOINT=0makes Python ignore everybreakpoint()call. For example,PYTHONBREAKPOINT=0 python3 script.pyruns the script without stopping.
When you have finished, delete the demo folder:
cd ~
rm -rf ~/pdb-demoCheck it worked
ls ~/pdb-demo reports No such file or directory. You can name the pdb command behind each editor button: Continue, Step Over, Step Into, and the conditional breakpoint.
Next steps
- Before you open the debugger, learn to get the most from the error message itself: read a Python traceback.
- Turn what you did here into a method for any bug, in any language: find a bug step by step.
- Use pdb to watch a list change in two places at once: understand variable references and mutability.
- The pdb page in the Python documentation at docs.python.org lists every command, including
displayto watch an expression anduntilto finish a loop.
Part of these paths
Related tutorials
- Find a bug step by step: reproduce, isolate, fix and checkYou will track down a wrong total in a short Python script by reproducing it, shrinking the input, testing one hypothesis at a time, fixing it, adding a test and writing a bug report.
- Read a Python traceback and fix the error it points toYou will run six short broken Python scripts, read each traceback from the bottom up to find the exception, the message and the line at fault, fix all six and keep a personal error log for the next time.
- Why changing one list changed another: references and mutability in PythonYou will reproduce three classic Python bugs where a list changes behind your back, learn how names refer to objects and which types can change, and end with a script that proves all three bugs are fixed.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials