Cohort 4Register

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.

A REAL TRACEBACKPYTHON 3.12
def average(values):
    return sum(values) / len(values)

orders = []
print(average(orders))

Output

ZeroDivisionError: division by zero
ErrorWhat it meansTypical causeFix
SyntaxErrorPython cannot read the lineMissing colon, bracket or quoteLook at the line and the one above
IndentationErrorSpacing is wrongMixed tabs and spaces, missing indent after :Use 4 spaces everywhere
NameErrorUnknown nameTypo, wrong capital, used before createdCheck spelling and order
TypeErrorWrong kind of value"5" + 5, calling a non-functionConvert types: int(), str()
ValueErrorRight type, bad valueint("abc"), float("")Validate or try/except
IndexErrorPosition does not existxs[10] on a 5-item listCheck len() first
KeyErrorKey not in the dictd["phone"] when there is noneUse d.get("phone")
ZeroDivisionErrorDividing by zeroAverage of an empty listCheck for empty first
FileNotFoundErrorNo such fileWrong name or folderCheck the path with pathlib
TRY / EXCEPT: HANDLE THE ERROR, KEEP GOINGPYTHON 3.12
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', '']
DEBUGGING: PRINT WHAT YOU HAVE, THEN ASSERT WHAT YOU EXPECTPYTHON 3.12
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

  1. Cause a KeyError on purpose and read the last line of the message.
  2. Return 0 instead of crashing when averaging an empty list.
  3. Fix "Total: " + 5 in two different ways.