The traceback is a map
Worked examples
Read the claim, then run it and check the machine agrees. One at a time — nothing here is taken on trust.
# A NameError, caught so the program keeps running.
try:
print(pirce) # 'pirce' was never defined
except NameError as e:
print(type(e).__name__) # the ErrorType, as text
print(e) # the message part
Instead of letting the error crash the run, try/except catches it so we
can look at it. type(e).__name__ is the headline word — it prints
NameError. print(e) shows the message: name 'pirce' is not defined.
One honest detail: the Did you mean: 'price'? suggestion you saw in the
slides is not in this printed message — Python adds that only when it
formats a full traceback. The plain error carries just the core sentence.
age = "40" # quotes make this TEXT, not a number
try:
print(age + 4) # gluing an int onto a str
except TypeError as e:
print(type(e).__name__)
print(e)
This prints TypeError, then can only concatenate str (not "int") to
str. Read literally: age is a str because of the quotes, and +
between a string and a number is undefined. The message hands you the two
types that clashed, which points straight at the fix: drop the quotes so
age is 40, a number.
shares = 0
try:
print(1000 / shares)
except ZeroDivisionError as e:
print(type(e).__name__)
print(e)
prices = [101, 102, 103] # positions 0, 1, 2 exist
try:
print(prices[5]) # there is no position 5
except IndexError as e:
print(type(e).__name__)
print(e)
The first block prints ZeroDivisionError and division by zero — you
asked Python to split 1000 into 0 groups. The second prints IndexError
and list index out of range: the list has three items at positions 0, 1
and 2, so asking for position 5 falls off the end. Both messages describe
the problem in plain words once you slow down and read them.
Check the concept
One question at a time. Unsure? Revisit the lecture, then answer.
The challenge
Pass the quiz to unlock the challenge — your code will still be waiting here.