Learn Python
>>> exception_handling.debugging_pdb

Debugging with pdb in Python

#concept

pdb is Python's built-in interactive debugger, letting a program pause mid-execution so its exact state — every variable's current value, the call stack, and more — can be inspected line by line. It's a far more precise way to understand what's actually happening than scattering temporary print() statements throughout code and rerunning it repeatedly.

#how it works
1

breakpoint() pauses execution

Built into Python 3.7+, it stops the program at that exact line.

2

A (Pdb) prompt appears

Accepting commands right there in the terminal, once paused.

3

n and s move forward

n (next) runs the current line; s (step) does the same but also steps into any function it calls.

4

p variable_name inspects state

Prints the current value of any variable in scope, right at that paused moment.

5

c resumes normal execution

Continues until the next breakpoint or the program’s natural end.

#example
def calculate_total(prices):
total = 0
for price in prices:
breakpoint()
total += price
return total
 
calculate_total([10, 20, 30])
Output
> example.py(5)calculate_total()
-> total += price
(Pdb) p price
10
(Pdb) p total
0
(Pdb) c
1breakpoint() pauses execution the moment the loop reaches it, on the very first iteration.
2Python drops into an interactive (Pdb) prompt, showing exactly which line execution is paused on.
3p price and p total print the current value of each variable at this exact paused moment — price is 10, and total hasn’t been updated yet, still 0.
4c resumes execution normally, running until it hits breakpoint() again on the next loop iteration, or the program simply finishes.
#use cases
Inspecting a variable's exact value at the precise moment something goes wrong, instead of guessing from scattered print() statements
Stepping through a function line by line to understand exactly how a tricky piece of logic actually behaves
Debugging a loop by pausing at a specific iteration instead of adding a print() and rerunning from scratch each time
Understanding what a stack trace means by walking up and down the actual call stack interactively with pdb's up and down commands

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.