Skip to main content

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:

Bash
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.py

What the script is meant to do:

  • average_usage(days) keeps a running total of megabytes and a count of 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__": runs main() 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:

Bash
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()
PY

Now run it:

Bash
python3 data_use.py

The program stops before printing anything and shows something like this:

Text
> /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:

Text
l
p mb
p total, count
p days
  • l (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) evaluates mb and shows its value: 120, the first reading.
  • p total, count shows both counters as a pair: (0, 0), because no line in the loop has run yet.
  • p days shows 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:

Bash
python3 data_use.py

At the (Pdb) prompt, type:

Text
n
n
n
p total, count
c
p mb
n
n
p total, count
  • n (next) runs the current line and stops at the next one in the same function. After three n commands you have gone past if mb > 0: and total += mb, and pdb shows -> count += 1, the line it is about to run.
  • p total, count now shows (120, 0): the reading has been added, and count is about to go up.
  • c (continue) lets the program run freely until it hits a breakpoint again. Because breakpoint() is inside the loop, that happens at the start of the next day.
  • p mb shows 0: this is a day with no reading.
  • Two more n commands. Watch which lines pdb shows. It goes from if mb > 0: straight to -> count += 1, skipping total += mb, which is right. But it still lands on count += 1.
  • p total, count shows (120, 1), and count += 1 is 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:

Bash
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

In this version, line 10 is count += 1 and line 16 is result = average_usage(usage). Start the script under pdb:

Bash
python3 -m pdb data_use.py

pdb stops before the first line of the file, at the docstring on line 1. Type:

Text
b 16
c
s
b 10, mb == 0
c
pp locals()
  • b 16 (break) sets breakpoint 1 on line 16. pdb confirms with Breakpoint 1 at ...data_use.py:16.
  • c runs until that breakpoint, so you stop in main() just before it calls average_usage.
  • s (step) runs the current line but, unlike n, follows it into any function it calls. pdb prints --Call-- and you are now at the top of average_usage. Use s when you want to go inside a function, n when you trust it and want to step over it.
  • b 10, mb == 0 sets breakpoint 2 on line 10, but only for days where mb == 0. The condition is any Python expression.
  • c runs 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, and pp lays out long values more readably than p.

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:

Bash
python3 -m pdb data_use.py
Text
b 10, mb == 0
c
w
u
p usage
d
p mb
q
  • w (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 see main() waiting at line 16, then average_usage() at line 10.
  • u (up) moves one frame towards the caller. You are now looking at main(). The program has not moved; only your view has.
  • p usage works here because usage is a variable in main(). In average_usage the same list is called days.
  • d (down) moves back to average_usage, and p mb shows 0 again.

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:

Bash
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.py

Check 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:

Bash
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:

Bash
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:

Text
p days
p total, count
q

p 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:

Bash
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.py

Check 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=0 makes Python ignore every breakpoint() call. For example, PYTHONBREAKPOINT=0 python3 script.py runs the script without stopping.

When you have finished, delete the demo folder:

Bash
cd ~
rm -rf ~/pdb-demo

Check 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

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.