Assertions and Invariants
An assertion states an assumption directly in code.
assert len(scores) > 0
If the condition is true, execution continues. If it is false, Python raises an
AssertionError.
Assertions are useful while learning because they make hidden assumptions visible.
What is an invariant?
An invariant is something that should remain true at a certain point in the program.
Inside a loop that sums scores, a useful invariant is:
total is the sum of the scores processed so far
In code, a simpler check may be:
assert total >= 0
if scores are known to be non-negative.
Assert before a risky operation
Division by length assumes the length is not zero:
average = total / len(scores)
Say that explicitly:
An assertion catches the assumption
Ready to run.
Without the assertion, the program would fail at division. With the assertion, the reason is named before the risky operation.
Assertions are not user input handling
Assertions are mainly for programmer assumptions. They are not a full way to handle every possible bad input from a user.
For public input, code should usually check and respond:
But while building and testing learning code, assertions are excellent small guards.
Write helpful messages
Assertions can include a message:
assert len(scores) > 0, "scores must not be empty"
The message should name the assumption, not blame the reader.
Which assertion checks that a list has at least one item?
Select one choice, then check.
HintExclude zero
An empty list has length zero. Choose a comparison that does not allow zero.
SolutionRequire a positive length
assert len(items) > 0 continues only when the list contains at least one
item. >= 0 would also allow an empty list.