Errors and debugging: be a bug detective
Every coder makes mistakes. Every single one. A mistake in code is called a bug, and finding it is detective work: look at the clues, find the line, fix it.
The big idea
Debugging means reading the clues your program gives you, finding the line that's wrong, and fixing just that line.
See it in code
Not every bug stops the program. Some just show the wrong thing. Compare these two lines and spot the one-letter difference:
total = 7
print("Total: ${total}")
print(f"Total: ${total}")Total: ${total}
Total: $7The first line is missing its f, so the curly brackets stayed switched off. The output was the clue: brackets on the screen mean the f is gone.
Strange output is a clue. Here a number was typed inside quotes by mistake, and the answer shows exactly what went wrong:
cookies = "12"
print(cookies * 2)
cookies = 12
print(cookies * 2)1212 24
1212 isn't math. It's the text "12" written twice. That tells you Python is holding text, so the quotes have to go.
When you can't see the bug, add a print inside the loop and watch the values change. This register's total comes out far too small:
sales = [3, 6, 12]
for sale in sales:
total = 0
total = total + sale
print("after a sale of", sale, "the total is", total)
print("Day's sales: $", total)after a sale of 3 the total is 3 after a sale of 6 the total is 6 after a sale of 12 the total is 12 Day's sales: $ 12
The clue is in the middle lines. The total never grows, because total = 0 is inside the loop and wipes it on every trip. Move that line above the loop and the bug is fixed.
The paint studio and the arcade give you friendly clues as well. Misspell a color and the studio says it doesn't know that color. The picture itself is a clue, too.
Try it yourself
Fix the register: move total = 0 above the for line and run it. The day's sales should be $ 21. Then delete your detective print, since its job is done.
The common mistake
Changing lots of things at once. If you edit five lines and the bug goes away, you won't know which edit fixed it. Change one thing, run it, and look again.
What it unlocks
Red error messages get easier once you know your types, since many bugs are text pretending to be a number. And print() is the detective tool you'll use most.