An assertion is a condition that we're claiming should be true at
this point in the program. Typically, it summarizes the state of the
program's variables. Assertions can help explain the relationships among
variables, review what has happened so far in the program, and show that
loops have the desired effect.
When a program is correct, all of the assertions are true no matter
what inputs are provided. When a program has an error, at least one
assertion winds up false for some combination of inputs.
Python directly supports assertions through an
statement. There are two forms:
〉 〈 ,
False, the program is in error; this statement raises
AssertionError exception. If the
program is correct, this statement does nothing more.
If the second form of the statement is used, and an
is given, an exception is raised
using the value of the expression. We'll cover exceptions in detail in
Chapter 17, Exceptions
. If the expression is a string, it
becomes an the value associated with the
There is an even more advanced feature of the
statement. If the expression evaluates to a
class, that class is used instead of
AssertionError. This is not widely used,
and depends on elements of the language we haven't covered yet.
Here's a typical example:
if a < b: max= b
if b < a: max= a
assert (max == a or max == b) and max >= a and max >= b
If the assertion condition is true, the program continues. If the
assertion condition is false, the program raises an
AssertionError exception and stops, showing
the line where the problem was found.
Run this program with
a equal to
b and not equal to zero; it will raise the
AssertionError exception. Clearly, the
statements don't set
max to the
b. There is a problem in the
statements, and the presence of the problem is
revealed by the assertion.