Menu

Debugging

Introduction

Debugging is the art of finding and fixing errors in your code. Python provides excellent tools for debugging, from simple print() statements to the powerful built-in debugger pdb.

Reading tracebacks

When Python encounters an error, it prints a traceback — a report showing exactly where the error occurred and why:

Traceback (most recent call last):
  File "main.py", line 5, in <module>
    result = divide(10, 0)
  File "main.py", line 2, in divide
    return a / b
ZeroDivisionError: division by zero

Read tracebacks from bottom to top: the last line tells you the error type, and the lines above show the call chain.

Debugging tools

# 1. print() debugging
def buggy_function(items):
    print(f"DEBUG: items = {items}")  # inspect values
    result = [x * 2 for x in items]
    print(f"DEBUG: result = {result}")
    return result

# 2. breakpoint() - built-in debugger (Python 3.7+)
def process(data):
    breakpoint()  # drops you into pdb
    return data * 2

# 3. Try/except for error handling
try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")
finally:
    print("This always runs")

Assignment

  1. Practice reading Python tracebacks by intentionally writing code with errors.
  2. Use breakpoint() to step through a simple function.
  3. Write a try/except block that handles ValueError when converting user input to a number.

Support me!

I am a software engineer giving back to the community - my name is Musila Peter. Join me in empowering learners around the globe by supporting SaneGenius!