pdb in Python

What is pdb?

pdb stands for “Python Debugger,” and it is the built-in interactive debugger for Python. It’s a powerful tool that allows developers to inspect and debug Python code during runtime. You can use pdb to set breakpoints, step through code, examine variables, and identify issues in your Python programs.

Step 1: Import the pdb module
First, you need to import the pdb module into your Python script or interactive session.

import pdb

Step 2: Set a breakpoint
You can set a breakpoint in your code by adding the following line where you want to start debugging:


This will pause the execution of your program at that point and allow you to interact with the debugger.

Step 3: Run your program
Execute your Python script as you normally would. When the code encounters the pdb.set_trace() line, it will stop, and you’ll be dropped into the debugger.

Step 4: Using pdb commands
Once in the debugger, you can use various commands to inspect and manipulate the code. Here are some common pdb commands:

  • n or next: Execute the current line and stop at the next line.
  • s or step: Step into the function call.
  • c or continue: Continue execution until the next breakpoint.
  • q or quit: Quit the debugger and terminate the program.
  • l or list: List the code around the current line.
  • p or print: Evaluate and print a Python expression.
  • h or help: Display a list of available commands or get help on a specific command.
  • b or break: Set a new breakpoint.
  • r or return: Continue execution until the current function returns.
  • u or up: Move up the call stack.
  • d or down: Move down the call stack.


Let’s create a simple Python script and use pdb to debug it:

def divide(a, b):
    result = a / b
    return result

x = 10
y = 0

result = divide(x, y)
print("Result:", result)

When you run this script, it will pause at the pdb.set_trace() line. You can then use pdb commands to inspect variables, step through the code, and identify the issue in the divide function.

For example, you can use the p command to check the values of x and y, and you’ll see that y is 0, which is causing a division by zero error. The pdb debugger helps you identify and fix such issues in your code.

Hello, I’m Anuj. I make and teach software.

My website is free of advertisements, affiliate links, tracking or analytics, sponsored posts, and paywalls.
Follow me on LinkedIn, X (twitter) to get timely updates when I post new articles.
My students are the reason this website exists, crafted with the affection and dedication they’ve shown. ❤️

Feedback Display