Introduction
Python offers multiple debugging tools and techniques for finding and fixing bugs.
Print Debugging (Simple)
# Use f-strings for context
print(f"Debug: x={x}, y={y}")
# Use assertions
assert x > 0, f"x must be positive, got {x}"
PDB Debugger
import pdb
def buggy_function(data):
pdb.set_trace() # Breakpoint
# Continue with 'c', step with 's'
result = complex_calculation(data)
return result
PDB Commands
| Command | Description |
|---|---|
n | Next line |
s | Step into function |
c | Continue to next breakpoint |
p var | Print variable |
l | List source code |
w | Show call stack |
Practice Problems
- Use pdb to trace through a function
- Set conditional breakpoints
- Inspect variables with pdb
- Use pdb.post_mortem() for exceptions
- Configure IDE debugger