Debugging Is Detective Work
Great debuggers are not smarter – they are more systematic. They resist randomly changing code and treat debugging like an investigation.
The Scientific Method for Bugs
- Reproduce: Make the bug happen consistently
- Isolate: Find the smallest code that causes it
- Hypothesize: What do you think is wrong?
- Test: Prove or disprove your theory
- Fix: Change one thing at a time
- Verify: Confirm nothing else broke
Print/Console Debugging
def process_orders(orders):
print(f"DEBUG: {len(orders)} orders received")
total = 0
for i, order in enumerate(orders):
subtotal = order["price"] * order["quantity"]
print(f"DEBUG: Order {i}: subtotal={subtotal}")
total += subtotal
print(f"DEBUG: Total={total}")
return total
Using the Python Debugger
import pdb
def problematic_function(data):
pdb.set_trace() # Execution pauses here
# n = next line, s = step into, p var = print, q = quit
result = complex_calculation(data)
return result
Binary Search Debugging
When you do not know where the bug is in 500 lines of code:
- Add a print statement in the middle
- If bug appears before it – look in first half
- If after – look in second half
- Repeat: each step halves your search space
Rubber Duck Debugging
Explain your code out loud to anything – a rubber duck, a coworker, your cat. Articulating the problem forces your brain to process it differently. Many bugs are discovered before you finish explaining.
When Truly Stuck
- Take a break – fresh eyes catch things tired eyes miss
- Search the exact error message in quotes
- Post on Stack Overflow with minimal reproducible example
- Ask a colleague for a fresh perspective
