Files, Errors and Modules · Robust Code · lesson 3 of 8
Assertions and defensive checks
about 12 minutes · free · runs in your browser
Stating what must be true
assert checks something you believe is already true, and raises AssertionError if
it is not:
def average(numbers):
assert len(numbers) > 0, "average of nothing is undefined"
return sum(numbers) / len(numbers)
The distinction worth holding on to:
assertcatches programmer mistakes — things that should be impossible. Python strips assertions out entirely when run with-O, so never use them to validate input that comes from outside your program.raisehandles expected bad input — a user typing letters into a number field.
Defensive checks at the top of a function are cheap and turn a confusing failure ten frames deeper into an obvious one right here.
Your turn: write set_temperature(celsius) that raises ValueError below absolute
zero (−273.15) and above 1000, and otherwise returns the value rounded to one decimal.
You start from this, and edit it in the browser:
def set_temperature(celsius):
# Reject impossible temperatures, otherwise return it rounded.
pass