Python Debugging Techniques
In this page:
Print Statement Debugging
Inserting print() statements at key points in your code to display variable values as execution proceeds is the simplest debugging technique there is -- no tools or setup required, though it does mean manually removing or commenting out the prints once you're done.
Example: Print Statement Debugging
def add(a, b):
print("a =", a, "b =", b)
return a + b
print(add(2, 3))
Using Assert Statements
An assert condition statement checks that a condition holds true at that point in the code, and raises AssertionError immediately if it doesn't. Asserts are useful for catching invalid internal state early, close to its actual source, rather than letting a bug surface confusingly somewhere downstream.
Example: Using Assert Statements
def divide(a, b):
assert b != 0, "b must not be zero"
return a / b
print(divide(10, 2))
The Logging Module
The built-in logging module is the production-grade replacement for scattered print statements: it supports severity levels (DEBUG, INFO, WARNING, ERROR), can be turned on or off without editing code, and can route output to files as easily as to the console.
Example: The Logging Module
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("Starting process")
logging.info("Process running")
Programmatic Tracebacks
Inside a try/except block, you can capture and print the full traceback of a caught exception programmatically (via the traceback module) instead of letting the exception crash the whole program. This lets you log detailed error information while still keeping the application running.
Example: Programmatic Tracebacks
import traceback
try:
1 / 0
except ZeroDivisionError:
traceback.print_exc()
The pdb Module Concept
pdb is Python's built-in interactive command-line debugger, letting you pause execution at a specific line (via breakpoint() or import pdb; pdb.set_trace()) and then step through code one line at a time, inspecting variables live as you go -- far more powerful than adding and removing print statements by hand.
Example: The pdb Module Concept
# import pdb; pdb.set_trace() # pauses execution here interactively
print("pdb lets you step through code line by line")
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- Python PEP 8 Style Guide
- Python Debugging Techniques
- Python Testing with unittest
- Python Common Mistakes
- Python Interview Questions
- Python map() & filter()
- Python reduce()
- Python zip() & enumerate()
- Python sorted() & key Functions
- Python Comprehensions Advanced
- Python Turtle Graphics
- Python tkinter Introduction
- Python tkinter Widgets
- Python pygame Introduction
- Python Mini Projects