Python Debugging
Master debugging techniques using print, logging, pdb debugger, and IDE tools to quickly identify and fix issues.
💻 Basic Debugging
# Print debugging
def calculate(a, b):
print(f"Debug: a={a}, b={b}")
result = a + b
print(f"Debug: result={result}")
return result
# Logging
import logging
logging.basicConfig(level=logging.DEBUG)
def process_data(data):
logging.debug(f"Processing {len(data)} items")
logging.info("Process started")
logging.warning("Low memory")
logging.error("Failed to process")
# Assert for assumptions
def divide(a, b):
assert b != 0, "Divisor cannot be zero"
return a / b🔧 PDB Debugger
import pdb
def buggy_function(x, y):
pdb.set_trace() # Breakpoint
result = x / y
return result
# PDB commands:
# n (next) - Execute next line
# s (step) - Step into function
# c (continue) - Continue execution
# p variable - Print variable
# l (list) - Show code context
# q (quit) - Exit debugger
# Post-mortem debugging
try:
buggy_code()
except Exception:
import pdb; pdb.post_mortem()
# Python 3.7+ breakpoint()
def modern_debug():
x = 10
breakpoint() # Built-in breakpoint
return x * 2🎯 Key Takeaways
- print(): Quick debugging output
- logging: Production-ready logging
- pdb: Interactive Python debugger
- breakpoint(): Modern breakpoint syntax
- IDE debuggers: Visual debugging in VS Code/PyCharm
- Stack traces: Read error messages carefully