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, b)
We've provided a string which includes information about the assertion. This string will be an argument to the exception object which is created.
An exception has two interesting features. Firstly, it's an object with arguments...