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

Python Debugging Techniques

Debugging is finding and fixing mistakes in your code, like being a detective looking for clues. Tools like printing, logging, and asserts help you see what is going on.

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)  # simplest debugging technique, just inspect the values
    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"  # raises AssertionError immediately if violated
    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)  # sets the minimum severity level to show
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()  # prints the full traceback without crashing the program

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")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Debugging only with print() and leaving those lines in the finished code.
  2. Using assert for validating user input, when assertions can be turned off with python -O.
  3. Ignoring the traceback, when its last line names the error and the lines above show where it happened.

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.