Reading a Traceback
In Python Basics, you learned to read an error message from the bottom: the last line says what went wrong, and the line above it says where. So far, that line has ended with in <module>, which means the main program, outside any function. When an error happens inside a function, the message has more lines:
def share(total, people):
return total / people
def print_bill(item, total, people):
print(f"{item}: {share(total, people)} each")
print_bill("Pizza", 36, 4)
print_bill("Cinema", 30, 0)This program prints one line and stops:
Pizza: 9.0 each
Traceback (most recent call last):
File "<exec>", line 8, in <module>
File "<exec>", line 5, in print_bill
File "<exec>", line 2, in share
ZeroDivisionError: division by zeroRead it from the bottom, one line at a time:
ZeroDivisionError: division by zero: the program divided by zero, which is impossible in math, and in Python too.line 2, in share: it happened on line 2, in the functionshare.line 5, in print_bill:sharewas called on line 5, in the functionprint_bill.line 8, in <module>: andprint_billwas called on line 8 of the main program.
Each File line is a call that was still running when the error happened. Together, they're called a traceback: they trace the error back to the line of your program where it all started. The heading most recent call last says that the last call, where Python stopped, is at the bottom.
So where's the mistake? Python stopped in share, but there's nothing wrong with dividing a bill. The 0 came from line 8: a bill for 0 people. The bottom of a traceback tells you where Python stopped, the lines above it how it got there, and the mistake can be at any of them. Look at the values each call passes on.
Python calls such errors exceptions. When something goes wrong while a program runs, Python raises an exception: it stops what it's doing and reports the problem. Each type of exception has a name. You know NameError, TypeError, ValueError, KeyError, IndexError and AttributeError, and now ZeroDivisionError too. So far, every exception has ended your program. In this lesson, you'll learn to catch them, so that the program can deal with the problem and go on.
Instructions
- 1
Run the program. It ends with a
NameError, and its traceback has threeFilelines. Read it from the bottom: in which function, and on which line, is the mistake? Fix it. The program then printsAnna: 12.0andEva: 18.0. - 2
Tom has joined the team but hasn't played yet. At the end of the program, add
print_average("Tom", []). The program now ends with aZeroDivisionError, and the traceback leads from your new line to the division inaverage(). This time the call is fine, since a player without games is nothing unusual, so fix the function: for an empty list,average()returns0(checklen(scores)before you divide). Leave the calls as they are. The last line is thenTom: 0.