Open in VS Code: From your cloned s26-06643 repository, run in the terminal:

code sse/07-debugging/07-debugging.ipynb

View source on GitHub

Module 07: Debugging & Profiling with AI#

Finding and fixing bugs systematically, with AI as your partner.

Learning Objectives#

  1. Develop a systematic approach to debugging

  2. Use Python’s built-in debugging tools (print, breakpoint, pdb)

  3. Read and interpret tracebacks effectively

  4. Use AI to diagnose and fix bugs

  5. Profile code to identify performance bottlenecks

  6. Know when to debug yourself vs. when to ask AI

Why Debugging Skills Matter#

AI generates code fast, but it also generates bugs fast. You will spend significant time:

  • Debugging AI-generated code that doesn’t quite work

  • Tracking down subtle issues AI introduced

  • Understanding why code that “looks right” fails

Debugging is a skill, not a talent. It follows a systematic process:

  1. Reproduce the bug reliably

  2. Isolate the problem to the smallest code

  3. Understand what’s actually happening vs. what you expect

  4. Fix the root cause, not the symptom

  5. Verify the fix and add a test

AI is excellent at steps 3 and 4 if you do steps 1 and 2 well.

Reading Tracebacks#

Python tracebacks are your first clue. Read them bottom to top:

Traceback (most recent call last):
  File "analysis.py", line 45, in main
    result = process_data(raw_data)
  File "analysis.py", line 23, in process_data
    normalized = [x / total for x in values]
ZeroDivisionError: division by zero

Reading this:

  • Bottom: The error type and message (ZeroDivisionError)

  • Middle: The exact line that failed (line 23, the list comprehension)

  • Top: How we got there (main called process_data)

Common Error Types#

Error

Typical Cause

NameError

Typo in variable name, forgot to define it

TypeError

Wrong type passed to function, wrong number of args

KeyError

Dictionary key doesn’t exist

IndexError

List index out of range

AttributeError

Object doesn’t have that method/property

ValueError

Right type, wrong value

ImportError

Module not installed or wrong name

AI Help with Tracebacks#

Pasting a full traceback into an AI agent is one of the most effective uses:

> I got this error when running my analysis:
  [paste full traceback]
  What's going wrong and how do I fix it?

AI excels at this because it has seen millions of tracebacks.

Context Engineering Reminder (from Module 00)

Before starting this exercise, think about what context the agent needs. For debugging, that means:

  • Paste the complete traceback — AI agents are excellent at reading tracebacks, but only if they can see the whole thing

  • Have the agent read the file where the error occurs, plus any files it imports

  • Run the failing command and show the output — concrete error messages are better than your description of the problem

Load the context first, then ask for the action.

Exercise 1: Reading Tracebacks (10 min)#

Look at the following code and traceback. Without running the code, answer:

  1. What error occurred?

  2. On which line?

  3. What is the root cause?

  4. How would you fix it?

def get_average_citations(authors):
    total = 0
    for author in authors:
        total += author['cited_by_count']
    return total / len(authors)

data = [
    {'name': 'Alice', 'cited_by_count': 150},
    {'name': 'Bob'},
    {'name': 'Carol', 'cited_by_count': 300},
]

avg = get_average_citations(data)
Traceback (most recent call last):
  File "example.py", line 13, in <module>
    avg = get_average_citations(data)
  File "example.py", line 4, in get_average_citations
    total += author['cited_by_count']
KeyError: 'cited_by_count'

Now paste this into your AI agent and compare its diagnosis with yours. Did it suggest a different fix than you thought of?

The Python Debugger: breakpoint() and pdb#

When print debugging isn’t enough, use the interactive debugger.

Setting a Breakpoint#

def calculate_h_index(citations):
    sorted_citations = sorted(citations, reverse=True)
    breakpoint()  # Execution pauses here
    h = 0
    for i, c in enumerate(sorted_citations, 1):
        if c >= i:
            h = i
    return h

When execution hits breakpoint(), you get an interactive prompt:

> calculate_h_index.py(4)calculate_h_index()
-> h = 0
(Pdb) 

Essential pdb Commands#

Command

Short

Description

next

n

Execute next line (step over)

step

s

Step into function call

continue

c

Continue to next breakpoint

print expr

p expr

Print expression value

list

l

Show code around current line

where

w

Show call stack

quit

q

Exit debugger

pp expr

Pretty-print expression

Example Session#

(Pdb) p sorted_citations
[10, 8, 5, 3, 1]
(Pdb) n
-> for i, c in enumerate(sorted_citations, 1):
(Pdb) n
-> if c >= i:
(Pdb) p i, c
(1, 10)
(Pdb) c

Post-mortem Debugging#

Debug after an exception has already occurred:

import pdb

try:
    result = buggy_function()
except Exception:
    pdb.post_mortem()  # Drop into debugger at the failure point

Exercise 2: Interactive Debugging (15 min)#

The function below has a bug. It should return a dictionary mapping author names to their h-index, but it’s returning wrong values.

Note: You saw a correct version of this function in Module 05 — this one has a subtle difference. Can you spot it before running the debugger?

  1. Create a file called buggy.py with this code

  2. Add a breakpoint() inside the loop

  3. Run the script and use pdb commands to inspect variables at each step

  4. Find the bug and fix it

def h_index(citations):
    citations_sorted = sorted(citations, reverse=True)
    h = 0
    for i, c in enumerate(citations_sorted):
        if c >= i:
            h = i
        else:
            break
    return h


def author_h_indices(authors):
    results = {}
    for author in authors:
        results[author['name']] = h_index(author['citations'])
    return results


authors = [
    {'name': 'Alice', 'citations': [10, 8, 5, 4, 3]},  # Expected h=4
    {'name': 'Bob', 'citations': [6, 5, 3, 1, 0]},     # Expected h=3
    {'name': 'Carol', 'citations': [0, 0, 0]},          # Expected h=0
]

result = author_h_indices(authors)
print(result)
# Should print: {'Alice': 4, 'Bob': 3, 'Carol': 0}

Hints:

  • Pay attention to what enumerate returns by default

  • Compare i and c at each iteration using p i, c

After you find the bug, ask AI to explain why the fix works.

Using AI to Debug#

AI agents are powerful debugging partners when you give them good context.

Effective Bug Reports for AI#

Give AI three things:

  1. The code (relevant parts, not your entire codebase)

  2. What you expected to happen

  3. What actually happened (error message or wrong output)

> This function should return the top N cited papers, but it's
> returning them in the wrong order:
>
> [paste function]
>
> Input: [paste example input]
> Expected: [paste expected output]
> Got: [paste actual output]

What AI is Good At#

  • Pattern matching: AI has seen common bugs millions of times

  • Off-by-one errors: Fence-post problems, wrong indices

  • API misuse: Wrong argument order, deprecated methods

  • Logic errors: Incorrect conditions, wrong operator

What AI Struggles With#

  • State-dependent bugs: Problems that depend on runtime state

  • Concurrency issues: Race conditions, deadlocks

  • Environment-specific bugs: OS differences, version conflicts

  • Data-dependent bugs: Issues that only appear with specific data

For these, you need to isolate the problem first (reproduce, simplify) before AI can help.

Exercise 3: AI-Assisted Debugging (10 min)#

The following function has a subtle bug. Try to find it yourself first (spend 2-3 minutes), then use AI to help.

def search_papers(papers, keywords):
    """Return papers whose titles contain ALL of the given keywords."""
    matches = []
    for paper in papers:
        title = paper['title'].lower()
        for keyword in keywords:
            if keyword.lower() in title:
                matches.append(paper)
                break
    return matches

papers = [
    {'title': 'Machine Learning for Catalysis'},
    {'title': 'Deep Learning Methods'},
    {'title': 'Catalysis Review'},
]

# Should return only the first paper (contains BOTH 'machine' and 'catalysis')
result = search_papers(papers, ['machine', 'catalysis'])
print([p['title'] for p in result])
# Actually returns: ['Machine Learning for Catalysis', 'Deep Learning Methods', 'Catalysis Review']
  1. What does the function actually do vs. what the docstring says?

  2. Paste the code and the bug description into your AI agent

  3. Compare the AI’s fix with what you came up with

  4. Which approach (yours or AI’s) is cleaner?

Logging#

For code that will run in production or be used by others, use logging instead of print:

import logging

logger = logging.getLogger(__name__)

def fetch_papers(query, limit=10):
    logger.info(f"Searching for: {query}, limit={limit}")
    
    response = requests.get(API_URL, params={"search": query})
    logger.debug(f"API response status: {response.status_code}")
    
    if response.status_code != 200:
        logger.error(f"API error: {response.status_code} - {response.text}")
        return []
    
    results = response.json()['results']
    logger.info(f"Found {len(results)} papers")
    return results

Log Levels#

Level

When to Use

DEBUG

Detailed diagnostic info (variable values, loop iterations)

INFO

Confirmation things are working (“fetched 10 results”)

WARNING

Something unexpected but not fatal

ERROR

Something failed

CRITICAL

Program can’t continue

Why Logging Beats Print#

  • Levels: Turn debug messages on/off without removing code

  • Output control: Log to file, console, or both

  • Timestamps: Know when things happened

  • No cleanup needed: Leave logging in production code

Profiling: Finding Performance Bottlenecks#

When code is slow, don’t guess where the bottleneck is. Measure it.

Quick Timing with time#

import time

start = time.time()
result = slow_function()
elapsed = time.time() - start
print(f"Took {elapsed:.2f} seconds")

IPython/Jupyter: %timeit and %%timeit#

# Time a single line
%timeit sorted(big_list)

# Time a cell
%%timeit
result = []
for x in big_list:
    result.append(x ** 2)

cProfile: Full Function Profiling#

python -m cProfile -s cumulative my_script.py

Or in code:

import cProfile

cProfile.run('main()', sort='cumulative')

Output shows time spent in each function:

   ncalls  tottime  cumtime  filename:lineno(function)
      100    0.500    2.300  api.py:15(fetch_data)
      100    1.800    1.800  {method 'read' of ...}
     1000    0.050    0.050  utils.py:8(normalize)

This tells you: fetch_data was called 100 times and took 2.3 seconds total, mostly waiting for network I/O.

Exercise 4: Profile and Optimize (15 min)#

The function below is slow. Profile it, identify the bottleneck, and use AI to help optimize.

import time

def find_common_coauthors(author_papers):
    """Find authors who appear in multiple paper author lists.
    
    author_papers: list of lists, where each inner list is
                   the author names on a paper.
    Returns: dict mapping author name to paper count.
    """
    coauthors = {}
    for i, paper in enumerate(author_papers):
        for author in paper:
            count = 0
            for other_paper in author_papers:
                if author in other_paper:
                    count += 1
            if count > 1:
                coauthors[author] = count
    return coauthors

# Generate test data
import random
random.seed(42)
names = [f"Author_{i}" for i in range(200)]
papers = [[random.choice(names) for _ in range(random.randint(2, 6))] 
          for _ in range(500)]

start = time.time()
result = find_common_coauthors(papers)
print(f"Found {len(result)} coauthors in {time.time() - start:.2f}s")

Steps:

  1. Run the code and note how long it takes

  2. Think about the time complexity — why is it slow?

  3. Ask AI: “This function is slow. Can you explain why and suggest an optimized version?”

  4. Compare the performance of the original vs. optimized version

  5. Verify both versions produce the same results

Debugging Strategies: A Decision Tree#

When something goes wrong, follow this process:

Bug found
  |
  +-- Is there an error message / traceback?
  |     +-- YES: Read the traceback bottom-to-top
  |     |        Can you understand it? -> Fix it
  |     |        Can't understand it? -> Paste into AI
  |     +-- NO: Wrong output (logic bug)
  |              |
  +-- Can you reproduce it reliably?
  |     +-- YES: Good, proceed to isolate
  |     +-- NO: Add logging, try to find pattern
  |
  +-- Can you isolate it to a small example?
  |     +-- YES: Use print debugging or breakpoint()
  |     +-- NO: Use binary search (comment out half the code)
  |
  +-- Still stuck after 10 minutes?
        +-- Ask AI with: code + expected + actual
        +-- Take a break and come back fresh

The 10-Minute Rule#

If you’ve been stuck on a bug for more than 10 minutes without making progress, change your approach:

  • Ask AI for help

  • Try a completely different debugging technique

  • Explain the problem out loud (“rubber duck debugging”)

  • Take a short break

Exercise 5: Full Debugging Workflow (15 min)#

Here’s a more realistic scenario. This code fetches and processes data but has multiple bugs.

import json

def load_research_data(filename):
    """Load research data from a JSON file and compute statistics."""
    with open(filename) as f:
        data = json.load(f)
    
    # Calculate average citations per year for each author
    stats = {}
    for author in data['authors']:
        name = author['name']
        years_active = 2026 - author['first_publication_year']
        avg_per_year = author['total_citations'] / years_active
        stats[name] = round(avg_per_year, 1)
    
    # Find the most productive author
    best = max(stats, key=stats.get)
    
    return {'per_year': stats, 'top_author': best}

Create a test JSON file (research_data.json):

{
    "authors": [
        {"name": "Alice", "first_publication_year": 2020, "total_citations": 150},
        {"name": "Bob", "first_publication_year": 2026, "total_citations": 0},
        {"name": "Carol", "first_publication_year": 2015, "total_citations": 500},
        {"name": "David", "total_citations": 200}
    ]
}
  1. Without running the code, how many bugs can you spot?

  2. Run the code and fix each bug as you encounter it

  3. Use a mix of your own debugging and AI assistance

  4. After fixing, write a test that would have caught each bug

Bugs to look for:

  • What happens when years_active is 0?

  • What if an author is missing a field?

  • Are there any edge cases in the data?

Summary#

Technique

Best For

Read the traceback

First step for any error

print() / f-string =

Quick variable inspection

breakpoint() / pdb

Stepping through complex logic

Logging

Production code, long-running processes

AI assistance

Pattern-matching known bugs, explaining errors

cProfile / %timeit

Finding performance bottlenecks

Key Takeaways#

  • Reproduce first, fix second – never fix a bug you can’t reproduce

  • Read the error message – Python tells you what went wrong

  • AI is great at debugging – but you need to give it good context

  • Don’t guess at performance – profile and measure

  • The 10-minute rule – change your approach if you’re stuck

Tips and Tricks#

  • Paste the full traceback: AI agents are excellent at reading tracebacks — give them the complete error, not a summary.

  • Prompt: “Explain this error and suggest three possible causes: [traceback]”: Getting multiple hypotheses is more useful than a single guess.

  • Add print statements strategically: Before asking AI to debug, add prints around the suspicious area and show the output — this gives the agent concrete data.

  • Prompt: “Add logging to [function] at DEBUG level”: Logging is more permanent than print debugging and costs almost nothing to leave in.

  • Reproduce first, fix second: Never ask the agent to fix a bug you cannot reproduce — it will guess, and guesses waste tokens.

  • Use breakpoint() for interactive debugging: Drop it in your code, run it, and explore the state — then describe what you found to the agent.

  • Prompt: “Write a minimal test that reproduces this bug”: A failing test is the best bug report and prevents regressions.

  • When stuck, describe the symptoms: “The function returns 0 instead of 42 when given [input]” is better than “it doesn’t work.”

Foundational Concepts to Commit to Memory#

  • Read tracebacks bottom to top – the error type and message are at the bottom, the chain of calls that led there is above, and the root cause is usually in the last few frames

  • breakpoint() drops you into an interactive debugger (pdb) at that exact line – use n (next), s (step into), p (print), c (continue), and q (quit)

  • f-string = syntax (print(f"{x=}")) prints both the variable name and its value, which is faster than writing print(f"x = {x}") everywhere

  • Reproduce before you fix – if you cannot reliably trigger the bug, you cannot verify your fix actually works

  • The 10-minute rule: if you are stuck for more than 10 minutes without progress, change your approach – ask AI, try a different technique, or take a break

  • Logging (import logging) is permanent, level-controlled instrumentation that stays in production code, unlike print statements which must be removed

  • Profiling (cProfile, %timeit) measures where time is actually spent – never guess at performance bottlenecks, always measure

  • Give AI good context for debugging: the code, what you expected, and what actually happened (including the full traceback) – the better your bug report, the better the AI’s diagnosis

Knowing vs. Doing: Reflection#

Debugging is fundamentally different from the other topics in this course because you cannot plan when you will need it. You do not sit down and say “today I will debug for two hours.” Bugs show up unexpectedly, often at the worst possible time, and your ability to resolve them quickly depends entirely on how well you understand the tools and techniques available to you. This is a domain where knowing really does translate directly into speed. A student who knows how to read a traceback, use breakpoint(), and structure a good question for AI will fix bugs in minutes that would take hours of frustrated guessing otherwise.

At the same time, debugging is one of the best places to lean on AI agents. Pasting a traceback into an AI and asking “what is going wrong?” is one of the highest-value interactions you can have. AI has seen millions of error messages and can pattern-match to common causes almost instantly. But the AI cannot reproduce your bug, inspect your runtime state, or understand the full context of your system. You still need to do the work of isolating the problem, creating a minimal reproduction, and verifying the fix. The AI accelerates the diagnosis, but you own the process.

There is a temptation to think that once you have AI helping you debug, you do not need to learn debugging techniques yourself. This is exactly backwards. The better you are at debugging, the better you are at describing problems to AI, evaluating its suggestions, and knowing when it is leading you astray. Debugging skill also builds your intuition about how code works, which makes you faster at everything else – writing, reviewing, and designing software. You will never stop encountering bugs, so invest in getting good at finding them.

Additional Resources#

Next Steps#

In the next module, we’ll learn GitHub collaboration workflows.