PART 1 · PYTHON FROM ZERO · LESSON 17
Reading errors without panic
FreeLesson 19 of 78
Errors are Python telling you exactly what went wrong and where. Learning to read them is faster than any amount of guessing.
def average(values):
return sum(values) / len(values)
orders = []
print(average(orders))Output
ZeroDivisionError: division by zero
| Error | What it means | Typical cause | Fix |
|---|---|---|---|
SyntaxError | Python cannot read the line | Missing colon, bracket or quote | Look at the line and the one above |
IndentationError | Spacing is wrong | Mixed tabs and spaces, missing indent after : | Use 4 spaces everywhere |
NameError | Unknown name | Typo, wrong capital, used before created | Check spelling and order |
TypeError | Wrong kind of value | "5" + 5, calling a non-function | Convert types: int(), str() |
ValueError | Right type, bad value | int("abc"), float("") | Validate or try/except |
IndexError | Position does not exist | xs[10] on a 5-item list | Check len() first |
KeyError | Key not in the dict | d["phone"] when there is none | Use d.get("phone") |
ZeroDivisionError | Dividing by zero | Average of an empty list | Check for empty first |
FileNotFoundError | No such file | Wrong name or folder | Check the path with pathlib |
rows = ["1198", "796", "abc", "", "1499"]
total, bad = 0, []
for r in rows:
try:
total += float(r) # might fail
except ValueError:
bad.append(r) # note it and keep going
print("total:", total, "| could not read:", bad)Output
total: 3493.0 | could not read: ['abc', '']
orders = [{"id": 101, "amount": "1198"}, {"id": 102, "amount": 796}]
total = 0
for o in orders:
kind = type(o["amount"]).__name__
print("DEBUG", o["id"], repr(o["amount"]), kind)
total += float(o["amount"])
print("total:", total)
assert total == 1994.0, f"expected 1994, got {total}"
print("check passed")Output
DEBUG 101 '1198' str DEBUG 102 796 int total: 1994.0 check passed
Try it yourself before moving on
- Cause a KeyError on purpose and read the last line of the message.
- Return 0 instead of crashing when averaging an empty list.
- Fix "Total: " + 5 in two different ways.