Errors Are Normal

Every programmer makes errors. Every single one.

The difference between beginners and experts isn't that experts don't get errors — they're just faster at fixing them.

Debugging (finding and fixing errors) is a core programming skill. AI makes debugging dramatically faster and less frustrating. But you still need to develop the problem-solving mindset.

Types of Errors

Syntax Errors

Syntax errors are like grammar mistakes. Python can't understand what you wrote.

# Missing colon
if x > 5
    print("big")  # SyntaxError!

# Mismatched parentheses
print("hello"     # SyntaxError!

# Indentation errors
def greet():
print("hello")    # IndentationError!

Python catches these before running. They're usually easy to fix once you see them.

Runtime Errors

Runtime errors happen while the program is running. The syntax was correct, but something went wrong.

# Division by zero
result = 10 / 0    # ZeroDivisionError!

# Accessing invalid index
numbers = [1, 2, 3]
print(numbers[10])  # IndexError!

# Using undefined variable
print(unknown_var)  # NameError!

# Type mismatch
"5" + 3            # TypeError!

Logic Errors

The worst kind. Your code runs without errors but does the wrong thing.

# Supposed to calculate average
def average(numbers):
    total = 0
    for n in numbers:
        total += n
    return total  # Bug! Should divide by len(numbers)

print(average([10, 20, 30]))  # Returns 60, should be 20

No error message. Just wrong results.

Reading Error Messages

Error messages are helpful once you learn to read them.

Anatomy of an Error

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

Breaking it down:

  • Traceback — The path that led to the error
  • File and line — Where the error occurred
  • Code — The line that caused the problem
  • Error type — ZeroDivisionError
  • Error message — "division by zero"

Read from bottom to top for the main error, then look at the path to understand how you got there.

AI Error Translation

When you get an error, use this prompt:

I got this error in Python:

[Paste the full error message]

Here's my code:

[Paste your code]

Explain:
1. What this error means in simple terms
2. Why it happened in my specific code
3. How to fix it

Don't just give me the fixed code — help me understand so I can fix similar errors myself.

The Debugging Process

Step 1: Reproduce the Error

Before fixing, make sure you can reliably trigger the error.

  • What input causes the problem?
  • Does it happen every time or randomly?
  • When did it start happening?

Step 2: Locate the Problem

Find exactly where things go wrong.

Use print statements:

def calculate(x, y):
    print(f"Received: x={x}, y={y}")  # Debug print
    result = x * y
    print(f"After multiply: {result}")  # Debug print
    result = result + 10
    print(f"After add: {result}")  # Debug print
    return result

Narrow down: Comment out parts of your code to isolate the problem section.

Step 3: Understand the Cause

Don't just fix symptoms. Understand why the error occurred.

Ask yourself:

  • What did I expect to happen?
  • What actually happened?
  • What's the difference between the two?

Step 4: Fix and Verify

Make the smallest change that fixes the problem. Then test:

  • Does the original error go away?
  • Did you break anything else?
  • Does it work with different inputs?

Step 5: Learn from It

After fixing:

  • Why did you make this mistake?
  • How can you prevent similar mistakes?
  • Is there a pattern in your errors?

AI-Assisted Debugging

Basic Debug Prompt

My code isn't working correctly.

What I expect: [describe expected behavior]
What happens: [describe actual behavior]

Here's my code:
[paste code]

Help me find the bug. Give me hints first before revealing the fix — I want to learn to debug myself.

Understanding Logic Errors

My code runs without errors, but gives wrong output.

Input: [what you're putting in]
Expected output: [what should happen]
Actual output: [what's happening]

Code:
[paste code]

Walk through my code line by line with this specific input. Where does my logic go wrong?

Rubber Duck Debugging with AI

"Rubber duck debugging" means explaining your code line by line (even to a rubber duck). The act of explaining often reveals the bug.

AI makes an excellent rubber duck:

I'm going to explain my code to you line by line. Stop me if anything sounds wrong or inconsistent.

[Then explain each line in your own words]

Learning from Fixed Code

When AI provides a fix:

You fixed my code. Now help me understand:

1. What was wrong with my original code?
2. Why does your fix work?
3. What principle or concept was I missing?
4. How should I think about this to avoid similar bugs?

Common Beginner Bugs

Off-By-One Errors

# Bug: misses the last item
for i in range(len(items) - 1):  # Should be range(len(items))
    print(items[i])

# Bug: goes one too far
for i in range(len(items) + 1):  # IndexError on last iteration
    print(items[i])

Variable Scope Issues

# Bug: using variable before assignment
def calculate():
    result = x + 10  # x isn't defined in this function!
    return result

# Bug: expecting global modification
count = 0
def increment():
    count = count + 1  # This creates a new local variable!

increment()
print(count)  # Still 0!

Mutation Surprises

# Bug: modifying list while iterating
numbers = [1, 2, 3, 4, 5]
for n in numbers:
    if n % 2 == 0:
        numbers.remove(n)  # Dangerous! Skips elements

# Bug: unintended alias
a = [1, 2, 3]
b = a           # b points to same list!
b.append(4)
print(a)        # [1, 2, 3, 4] — a was modified too!

Comparison Mistakes

# Bug: assignment instead of comparison
if x = 5:      # SyntaxError! Should be ==
    print("x is 5")

# Bug: comparing wrong things
if name == "alice" or "bob":  # Always True!
    # Should be: if name == "alice" or name == "bob":

Type Confusion

# Bug: string vs number
age = input("Enter age: ")  # Returns string!
if age > 18:    # Error: comparing string to int
    print("Adult")
# Fix: age = int(input("Enter age: "))

Debugging Strategies

Binary Search Debugging

If you have lots of code and don't know where the bug is:

  1. Put a print statement halfway through
  2. Does the bug appear before or after that point?
  3. Narrow your search to that half
  4. Repeat until you find it

Minimal Reproduction

Create the smallest possible code that reproduces the bug:

  1. Copy your buggy code
  2. Remove everything unrelated to the bug
  3. Keep removing until the bug disappears
  4. The last thing you removed was likely the cause

Fresh Eyes Approach

When stuck:

  1. Take a short break (seriously)
  2. Explain the problem to AI from scratch
  3. Don't assume you know where the bug is
  4. Question your assumptions

Building Debug Skills

Intentional Practice

Ask AI to create buggy code for you to fix:

Create a Python function with 3 bugs hidden in it. The function should calculate the average of numbers in a list.

Don't tell me what the bugs are. I'll try to find and fix them. Then I'll check my work with you.

Error Journal

Keep track of bugs you encounter:

  • What was the error?
  • What caused it?
  • How did you find it?
  • How did you fix it?

Patterns will emerge. You'll get faster at recognizing your common mistakes.

Predict Before Running

Before running code, predict:

  • What will the output be?
  • Any errors expected?
  • What value will variables have at each step?

Then run and compare. Mismatches teach you something.

When to Ask for Help

Ask AI when:

  • You've spent 15+ minutes stuck
  • You don't understand the error message
  • You need to learn a new concept to solve the problem
  • Your debugging attempts aren't narrowing things down

But try first:

  • Read the error message carefully
  • Add print statements
  • Check your assumptions
  • Re-read the code line by line

The struggle is where learning happens. But don't struggle forever.

Debug Prompts Cheat Sheet

Generic debug:

This code doesn't work: [code]
Error: [error message]
Help me understand what's wrong.

Logic error:

This runs but gives wrong output.
Expected: [x]
Got: [y]
Trace through my code with input [z].

Learn from fix:

You fixed my bug. What concept was I missing? How do I avoid this?

Practice:

Give me buggy code to fix. Don't reveal the bugs until I ask.

Stuck:

I've been stuck for [time]. Here's what I've tried: [attempts].
Give me a hint, not the answer.

What's Next

You understand concepts. You can debug errors. Now it's time to build real things.

Chapter 5 guides you through building your first projects — going from idea to working code with AI as your partner.