🛟 Errors & Exceptions, lesson 2 of 6
Common exception types
Meet the errors you'll see most and what usually causes them.
9 min
1 exercise
2 quizzes
0/3 solved
Getting Python ready… examples can run in a moment.
Python has dozens of built-in exceptions, but a handful cause most crashes. Knowing them by name lets you guess the fix from the last line alone:
- NameError: a name that doesn't exist (a typo, or used before it's defined)
- TypeError: the wrong type for an operation, like
"3" + 4orlen(5) - ValueError: right type, bad value:
int("hi") - IndexError: a list index past the end
- KeyError: a missing dictionary key
- ZeroDivisionError: dividing by zero
- AttributeError: no such method or attribute,
like
[1, 2].upper()
TypeError: mixing types
Fix it with str(age) or an f-string. Then try
len(5) to see a different TypeError message.
ValueError: right type, wrong value
int() accepts a string, but only one that looks like
a whole number. Try int("3.5") and int(" 7 ") too.
Which exception does this code raise?
Safer alternatives
colors[-1] always gets the last item, and
dict.get() returns a default instead of crashing.
Only the last line fails.
Which exception does this code raise?
Crash-proof the shopping list
Each numbered line crashes. Fix all three (without deleting them) so that:
lastis the last item initemsbread_priceis the price of bread, or0if it has no pricesummaryis the text"Items: 3"