Introduction

Python's built-in debugger, pdb, is a powerful tool that allows you to inspect and control the execution of your Python programs. It helps you identify and fix bugs by providing an interactive environment where you can set breakpoints, step through code, and examine variables.

Key Concepts

  1. Breakpoints: Points in the code where the execution will pause, allowing you to inspect the state of the program.
  2. Stepping: Executing the program one line at a time to closely monitor its behavior.
  3. Inspecting Variables: Viewing the values of variables at different points in the program.
  4. Call Stack: Understanding the sequence of function calls that led to the current point in the program.

Basic Commands

Here are some essential pdb commands:

Command Description
break or b Set a breakpoint at a specified line or function.
continue or c Resume execution until the next breakpoint.
step or s Execute the current line and stop at the first possible occasion (in a function that is called).
next or n Continue execution until the next line in the current function is reached.
list or l Display the source code around the current line.
print or p Evaluate and print the expression.
quit or q Exit the debugger and terminate the program.

Practical Example

Let's walk through a practical example to demonstrate how to use pdb for debugging.

Example Code

Consider the following Python script that calculates the factorial of a number:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

if __name__ == "__main__":
    number = 5
    result = factorial(number)
    print(f"The factorial of {number} is {result}")

Using pdb

  1. Import pdb and Set a Breakpoint: Insert the following line before the function call to start the debugger:

    import pdb; pdb.set_trace()
    

    The modified script looks like this:

    def factorial(n):
        if n == 0:
            return 1
        else:
            return n * factorial(n - 1)
    
    if __name__ == "__main__":
        import pdb; pdb.set_trace()
        number = 5
        result = factorial(number)
        print(f"The factorial of {number} is {result}")
    
  2. Run the Script: Execute the script in the terminal:

    python script.py
    
  3. Interactive Debugging: The execution will pause at the pdb.set_trace() line, and you will enter the pdb interactive mode. You can now use pdb commands to debug the script.

    • Set a Breakpoint:

      (Pdb) b factorial
      

      This sets a breakpoint at the start of the factorial function.

    • Continue Execution:

      (Pdb) c
      

      The program will run until it hits the breakpoint at the factorial function.

    • Step Through Code:

      (Pdb) s
      

      Step into the factorial function.

    • Inspect Variables:

      (Pdb) p n
      

      Print the value of n.

    • Continue Execution:

      (Pdb) c
      

      Continue execution until the next breakpoint or the end of the program.

Practical Exercise

Exercise

Modify the following script to use pdb for debugging. Set breakpoints and step through the code to understand its behavior.

def sum_of_squares(n):
    total = 0
    for i in range(1, n + 1):
        total += i * i
    return total

if __name__ == "__main__":
    number = 5
    result = sum_of_squares(number)
    print(f"The sum of squares up to {number} is {result}")

Solution

  1. Import pdb and Set a Breakpoint:

    def sum_of_squares(n):
        total = 0
        for i in range(1, n + 1):
            total += i * i
        return total
    
    if __name__ == "__main__":
        import pdb; pdb.set_trace()
        number = 5
        result = sum_of_squares(number)
        print(f"The sum of squares up to {number} is {result}")
    
  2. Run the Script:

    python script.py
    
  3. Interactive Debugging:

    • Set a Breakpoint:
      (Pdb) b sum_of_squares
      
    • Continue Execution:
      (Pdb) c
      
    • Step Through Code:
      (Pdb) s
      
    • Inspect Variables:
      (Pdb) p n
      (Pdb) p total
      

Conclusion

Using pdb for debugging allows you to interactively inspect and control the execution of your Python programs. By setting breakpoints, stepping through code, and inspecting variables, you can identify and fix bugs more efficiently. Practice using pdb with different scripts to become proficient in debugging Python code.

Python Programming Course

Module 1: Introduction to Python

Module 2: Control Structures

Module 3: Functions and Modules

Module 4: Data Structures

Module 5: Object-Oriented Programming

Module 6: File Handling

Module 7: Error Handling and Exceptions

Module 8: Advanced Topics

Module 9: Testing and Debugging

Module 10: Web Development with Python

Module 11: Data Science with Python

Module 12: Final Project

© Copyright 2024. All rights reserved