← Back to Python Course | Chapter 14: Advanced Python & Tools | Lesson 2 of 15

Python Debugging Techniques

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

python
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

python
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

python
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

python
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

python
# import pdb; pdb.set_trace()  # pauses execution here interactively
print("pdb lets you step through code line by line")

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.