When Things Break: Becoming a Code Detective (and Life Problem-Solver)
What You'll Learn
How to read error messages, find bugs systematically, and fix broken code — using the same scientific thinking that solves mysteries in real life.
Part 1
Bugs Are Normal
Here's a secret that professional programmers won't always admit: code almost never works the first time. Even experts write code that breaks. The difference between a beginner and an expert isn't that experts make fewer mistakes — it's that experts are better at finding and fixing them.
Finding and fixing problems in code is called debugging. And it's actually one of the most important skills you can learn — not just for coding, but for life. Debugging is just applied problem-solving:
Something isn't working → Figure out what's wrong → Fix it → Check if it's fixed
That's the same process for fixing a bike chain, figuring out why your friend is upset, or diagnosing why your Wi-Fi is slow. Today, you're going to become a code detective.
Part 2
Error Messages Are Clues, Not Punishments
When Python hits a problem, it gives you an error message. Most beginners panic when they see red text. But error messages are actually the most helpful thing Python does — they tell you exactly what went wrong and where.
Let's look at some common errors. Run each one and read the error message carefully:
NameError
What it means: Python doesn't recognize a name. Usually a typo or a variable you forgot to create.
How to fix: Check spelling carefully. Did you define the variable before using it?
TypeError
What it means: You tried to do something with the wrong type. Here, + can't join a string and a number.
How to fix: Convert the number to a string: str(age). Or use an f-string: f"I am {age} years old".
IndexError
What it means: You asked for position 5, but the list only goes up to position 2 (three items: 0, 1, 2).
How to fix: Check your list length with len(). Remember counting starts at 0!
SyntaxError
What it means: Python can't parse your code — it doesn't follow the rules of the language. Like a sentence with missing punctuation.
Common causes: Missing colon : after if/for/def. Missing quotation mark. Mismatched parentheses. Wrong indentation.
Part 3
The Detective's Method
Professional debuggers follow a systematic process. It's the same process a detective uses to solve a case:
The 4-Step Debugging Method
1. Observe: What's happening? What did you expect? What actually occurred?
2. Hypothesize: What could be causing this? Form a theory.
3. Test: Add print() statements to check your theory. Is the data what you think it is?
4. Fix and verify: Make the change. Run the code. Did it work?
This is deductive reasoning (Lesson 3) + inductive reasoning (Lesson 7) working together. You use rules to narrow down where the problem could be, and you use observations to test your theories.
Part 4
Case 1: The Broken Score Calculator
This program should calculate a student's average score, but it gives the wrong answer. Your mission: find and fix the bug.
Detective Work
Observe: The average should be 88, but it's not. The total looks wrong too.
Hypothesize: The total isn't adding up correctly. Look at line 9.
The bug: total = score replaces total each time instead of adding to it. After the loop, total just equals the last score (95).
The fix: Change total = score to total = total + score. Try it!
Part 5
Case 2: The Nonsense Name Generator
This program should create spy names by combining a random adjective with a random animal. But something's off...
Detective Work
Observe: The names look wrong. "Agent Shadow Silent"? Both parts are adjectives!
Hypothesize: Maybe both random picks are from the same list.
The bug: Line 12 says random.choice(adjectives) but it should say random.choice(animals). A copy-paste mistake!
The fix: Change adjectives to animals on line 12. Fix it and run again!
Part 6
Case 3: The Impossible Guessing Game
This number guessing game never lets you win, even when you guess correctly. What's going on?
Detective Work
Observe: Even when you type the right number, it never says "Correct!" Instead you might get a strange error or it just doesn't match.
Hypothesize: Maybe the comparison isn't working. Let's think about types...
The bug: input() gives you text. secret is a number. "5" == 5 is False in Python — text and numbers are never equal!
The fix: Change guess = input("Your guess: ") to guess = int(input("Your guess: ")). We learned this in Lesson 2!
Part 7
Case 4: The Unfair Quiz
This quiz always says "Wrong!" even when you answer correctly. Multiple bugs this time!
Detective Work — Two Bugs!
Bug 1: If you type "mercury" instead of "Mercury", it says wrong. The comparison is case-sensitive. Fix: compare answer.lower() == question["a"].lower().
Bug 2: The percentage shows 0.666... instead of 66%. Fix: multiply by 100 and convert to int: int(score / len(questions) * 100).
Fix both bugs and run it again. The quiz should now accept answers in any capitalization and show proper percentages.
Part 8
Case 5: The Backwards Logic
This grade calculator gives everyone the wrong grade. The code runs without errors — but the logic is wrong. These are the hardest bugs to find because Python doesn't complain.
Detective Work — Logic Bug
Observe: Score 95 gets "D" instead of "A". Score 85 also gets "D".
Hypothesize: Remember from Lesson 3 — if/elif checks from top to bottom and stops at the first match.
The bug: 95 is >= 60, so the FIRST condition matches and it returns "D". It never even checks the others!
The fix: Reverse the order — check the highest grade first: if score >= 90, then elif score >= 80, etc. The most specific conditions must come before the more general ones.
Part 9
Your Debugging Toolkit
Here's a summary of techniques you can use anytime code isn't working:
Debugging Techniques
1. Read the error message — it tells you the error type and often the line number.
2. Print debugging — add print() to see what variables contain at each step. Remove them when the bug is fixed.
3. Test with simple data — if your code breaks with complex input, try the simplest possible input first.
4. Check your assumptions — is that variable really a number? Is that list really the length you think?
5. Rubber duck debugging — explain your code line by line to an imaginary duck (or a real friend). Often you'll spot the bug while explaining.
6. Undo and retry — if you changed something and it got worse, undo it and try a different approach.
Part 10
The Final Case: Fix the Complete Game
This Rock Paper Scissors game has 4 bugs. Can you find and fix them all?
Hints (only look if you're stuck!)
Bug 1: If you type "Rock" instead of "rock", what happens? The comparison is case-sensitive.
Bug 2: Look at the line after "paper beats rock." Compare it to the other win lines. See the difference?
Bug 3: This one is tricky — the score display actually works fine! Sometimes you think there's a bug but there isn't. Good detectives rule out false leads too.
Bug 4: The "You won!" message shows up even if the computer won. It should check who actually won.
Part 11
What You Just Did
You practiced the most underrated skill in programming: debugging. You read error messages, formed hypotheses, tested them, and fixed broken code — all using the thinking skills you've built across the entire course.
Debugging uses every thinking skill we've learned:
Every Skill in Action
Decomposition: Break the problem into smaller questions. "Does the input work? Does the calculation work? Does the output work?"
Abstraction: Ignore irrelevant code and focus on the part that's broken.
Deductive reasoning: "If this variable is a string, then this comparison will fail."
Pattern recognition: "This bug looks like the int/string confusion from Lesson 2."
Inductive reasoning: "It works for inputs A and B but fails for C. What's different about C?"
The Big Idea
Bugs aren't failures — they're puzzles. Every bug you fix makes you a better programmer. The process of debugging — observe, hypothesize, test, fix — is the same process scientists use to understand the world. The skill isn't writing perfect code. It's knowing what to do when code isn't perfect.
Thinking Questions
- Which type of bug is harder to find — an error that Python catches (like NameError) or a logic bug where the code runs but gives wrong results? Why?
- Why is "print debugging" (adding print statements) so effective? What does it help you see?
- Can you think of a time in real life when you debugged something? (Finding out why something wasn't working and fixing it step by step?)
Challenges
Level Up
Challenge 1 · Bug Hunt
Go back to any project from a previous lesson (playlist manager, RPS tournament, friendship calculator) and intentionally break it in 3 different ways. Give the broken version to a friend and see if they can find all 3 bugs.
Challenge 2 · Error-Proof Input
Write a function safe_int_input(prompt) that asks for a number, and if the user types something that isn't a number (like "abc"), it says "Please enter a number" and asks again instead of crashing. Use a while True loop with try/except (search for "Python try except" if curious!).
Challenge 3 · Debug Log
Create a function debug(message, variable) that prints formatted debug info: [DEBUG] message: variable (type: type). Use it to debug a program by tracking variables as they change. This is building your own debugging tool!
Summary
What You Learned
Thinking Skill
Scientific Debugging — observe what's wrong, hypothesize a cause, test your theory, fix and verify. This combines deductive and inductive reasoning into a powerful problem-solving process.
Common Bug Types
NameError — typo in a variable name, or using a variable before defining it
TypeError — mixing incompatible types (string + number)
IndexError — accessing a list position that doesn't exist
SyntaxError — missing colons, quotes, or parentheses
Logic errors — code runs but gives wrong results (hardest to find!)
Off-by-one errors — loops running one too many or too few times
Debugging Techniques
Read error messages carefully (they're clues!)
Add print() to see variable values at each step
Test with simple inputs first
Check types: type(variable)
Rubber duck debugging — explain your code out loud
Check the order of if/elif conditions