Summary
In this lesson, you learned that:
- Python calls errors exceptions. Each type has a name:
NameError,TypeError,ValueError,KeyError,IndexError,AttributeError, andZeroDivisionErrorfor dividing by zero. - A traceback has a
Fileline for every call that was running when the exception was raised, from the main program (in <module>) at the top to the line where it happened at the bottom. Read it from the bottom: the type and the message, the line and the function, then who called it. The mistake can be at any of these lines. tryandexcept ValueError:catch an exception. When a line in thetryblock raises aValueError, the rest of the block is skipped, theexceptblock runs, and the program goes on.- Name the exception you expect. Of several
exceptblocks, the first one whose type matches runs, andexcept (ValueError, KeyError):catches both types. A bareexcept:catches everything, your own mistakes too, and hides them. except ValueError as error:stores the exception in a variable, andprint(error)prints its message.elseruns when thetryblock raised nothing, andfinallyalways runs.raise ValueError("The age can't be negative.")raises an exception with your message. A function raises one when its data make no sense. Likereturn, it ends the function.- An exception goes up from the function that raised it to the code that called it, until a
trycatches it. In a loop, atryaround one item skips just that item, and the loop goes on.
Now some practice. In the first exercise of this lesson, average() returned 0 for an empty list. But a player without games has no average, and 0 looks like a real one. This time, the function raises an exception.
In the next lesson, Modules, you'll learn to use code that comes with Python: with import, your programs get the mathematical functions of math, random numbers and more.
Instructions
- 1
Write a function
average(scores)that returns the average of the points in the listscores. For an empty list, it raises aValueErrorwith the messageNo games yet.instead. - 2
Below, go through
playerswith.items()and print each player's average with one decimal place, such asAnna: 12.0. Callaverage()in atryblock, and when it raises aValueError, print the message of the exception instead:Tom: No games yet.Keep the points as they are: the exercise also tries other points.