Logo
READLEARNKNOWCONNECT
Back to Lessons

    Page

  • - Why Debugging Matters
  • - Using Print Statements
  • - Understanding Tracebacks
  • - Using the pdb Debugger
  • - Using Logging for Debugging
  • - Common Python Errors
  • - Best Practices for Debugging
  • - Mini Exercise

27. Debugging Techniques in Python

Level: BeginnerDuration: 30m

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.

python
def divide(a, b):
    print(f"a={a}, b={b}")
    return a / b

result = divide(10, 2)
print(result)
💡 Print debugging is quick but can clutter your code. Remember to remove or comment out print statements in production.

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.

python
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.

python
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 TypeDescriptionExample Fix
NameErrorVariable not definedEnsure the variable is declared before use
TypeErrorIncorrect data type operationCheck variable types before performing operations
ZeroDivisionErrorDivision by zeroAdd checks to prevent division by zero
IndexErrorList index out of rangeVerify index values are within the list length
KeyErrorDictionary key missingUse .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.