Skip to main content

22. Debugging with pdb

Python includes a built-in debugger module called pdb for interactive debugging.


Running a Script with pdb

python -m pdb script.py

Inserting a Breakpoint

import pdb; pdb.set_trace()

x = 10
y = 20
z = x + y # execution will pause here

Common pdb Commands

  • n: next line
  • s: step into function
  • c: continue execution
  • q: quit debugger
  • p var: print variable value

Practice Challenge

Debug a function that incorrectly calculates the factorial of 5. Use pdb to step through and find the bug.


Wrap-Up

pdb provides an interactive way to inspect program state step by step.