Rocket pins a big sheet of paper to the wall and writes every error name he has seen so far. The list is longer than he expected.
"It is like a field guide," Raven says, delighted, and adds a column for what each one means. "What do you notice?" she asks. "Each name tells you the kind of problem before you even read the rest."
Nova adds one more row at the bottom, with no error name in it at all. "Interesting," she says. "The trickiest bugs give no error. The program runs, but the answer is wrong."
Rocket frowns at the empty row. "How do you find a bug that does not announce itself?" he asks.
Nova blinks. "You make the program show you what it is doing."
| Error | Usually means | Example |
|---|---|---|
| SyntaxError | Python cannot read the line | print("hi" (missing bracket) |
| IndentationError | The spaces at the start are wrong | no indent after if x: |
| NameError | A name is misspelled or not made yet | prnt("hi") |
| TypeError | Types that do not mix | "Fuel: " + 50 |
| ValueError | Right type, unusable value | int("ten") |
| IndexError | No item at that position | planets[10] |
| KeyError | No such key in a dictionary | probe["speed"] |
| ZeroDivisionError | Dividing by zero | 5 / 0 |
| FileNotFoundError | No file with that name here | open("misssing.txt") |
A logic bug runs without any error, but gives the wrong answer. Python cannot spot it, because the code is valid. You have to notice that the output is wrong.
The best tool is a test you can check by hand, plus a temporary print that shows the values inside the loop.
# count_full.py (has a logic bug)
tanks = [80, 50, 30, 95]
full = 0
for t in tanks:
print("checking", t) # temporary debug print
if t > 50:
full = full + 1
print("Tanks at 50 or more:", full) checking 80 checking 50 checking 30 checking 95 Tanks at 50 or more: 2
One of the most common logic bugs is being off by one. A range that stops one number too early gives an answer that looks almost right.
# sum_bug.py (should add 1 to 10, but has a bug)
total = 0
for n in range(1, 10):
total = total + n
print("Total:", total) | Statement | True or false? |
|---|---|
| A logic bug always shows a red traceback. | ? |
| Checking against an answer worked out by hand can reveal a logic bug. | ? |
| A temporary debug print should be deleted when the bug is fixed. | ? |
| "Fuel: " + 50 causes a TypeError. | ? |
You can now name most errors at a glance, and hunt bugs that hide. Tomorrow you will teach your programs to handle errors without stopping.