Overview
Teaching: 5 min
Exercises: 10 minQuestions
How can I make programs more robust?
How can I make programs easier to understand?
Objectives
Add
assert
statements to programs to check pre-conditions, post-conditions, and invariants.
assert condition, 'message'
halts with an error message if the condition isn’t true.
def bounds(values):
assert len(values) > 0, 'Cannot get bounds of empty list.'
low = min(values)
high = max(values)
assert low <= high, 'Low bound should not be greater than high bound'
return low, high
def average(values):
"Return average of values, or None if no values are supplied."
if len(values) == 0:
return None
return sum(values) / average(values)
help(average)
Help on function average in module __main__:
average(values)
Return average of values, or None if no values are supplied.
Multiline Strings
Often use multiline strings for documentation. These start and end with three quote characters (either single or double) and end with three matching characters.
"""This string spans multiple lines. Blank lines are allowed. For documentation, typically a first line summarizes the functionality, and a blank line separates that summary from the remainder. The ending three quote characters, in the case of a long documentation string, are typically on their own line. """
Document This
Clean Up This Code
Key Points
Fail early, often, and meaningfully.
Use
assert
to check that programs are working correctly.Give
assert
statements meaningful error messages to help users.