27. Debugging Techniques in Python
Why Debugging Matters
Debugging is the process of finding and fixing bugs in your code. Efficient debugging saves time, improves code quality, and prevents frustrating runtime errors.
Using Print Statements
The simplest way to debug is to print variable values and program flow checkpoints.
def divide(a, b):
print(f"a={a}, b={b}")
return a / b
result = divide(10, 2)
print(result)Understanding Tracebacks
Python provides detailed error messages (tracebacks) that show where an error occurred. Read the traceback from bottom to top to find the source of the problem.
Using the pdb Debugger
Python's built-in debugger `pdb` allows you to step through your code, inspect variables, and execute commands interactively.
import pdb
def divide(a, b):
pdb.set_trace() # pause execution here
return a / b
result = divide(10, 0)
print(result)Common `pdb` commands include: - `n`: go to the next line - `c`: continue until next breakpoint - `l`: list source code - `p variable`: print variable value - `q`: quit debugger
Using Logging for Debugging
The `logging` module is more powerful than print statements because you can control log levels, output to files, and leave debugging info in production code safely.
import logging
logging.basicConfig(level=logging.DEBUG)
def divide(a, b):
logging.debug(f'a={a}, b={b}')
return a / b
result = divide(10, 2)
print(result)Common Python Errors
| Error Type | Description | Example Fix |
|---|---|---|
| NameError | Variable not defined | Ensure the variable is declared before use |
| TypeError | Incorrect data type operation | Check variable types before performing operations |
| ZeroDivisionError | Division by zero | Add checks to prevent division by zero |
| IndexError | List index out of range | Verify index values are within the list length |
| KeyError | Dictionary key missing | Use .get() or check key exists before access |
Best Practices for Debugging
- Reproduce the bug consistently before fixing.
- Isolate the issue to a small section of code.
- Use version control to test changes safely.
- Write tests to ensure bug fixes don’t break other parts of code.
- Use debugging tools like pdb or logging instead of random print statements for complex projects.
Python Debugging with pdb and Logging
Mini Exercise
Take a small Python script that reads from a list of numbers and divides them by a user input. Introduce a bug (like dividing by zero) and practice debugging it using print statements, pdb, and logging.