The assert statement

The assert statement is a highly specialized form of if statement. This statement confirms that a given condition is true. If the condition is not true, the assert statement raises an exception. In the simplest case, the script stops running because the exception is not handled in our programming.

It looks like this:

assert a > b >= 0

We have used an assert statement to provide documentation of a relationship between variables that must be true at a given point in our Python script, function, or method. If the condition, a > b >= 0, is false, then the AssertionError exception is raised.

We can customize the exception which is raised by providing a second argument to the assert statement:

assert a > b >= 0, "a={0} and b={1}".format(a, ...

Get Python Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.