The assert
statement is a sanity check statement, used when debugging code.
It is an alternative to an if statement. It gives an AssertionError exception if the expression inside the assert evaluates to be false and no error. It is basically an internal self-check within the code.
Assertion statement takes an expression and an optional error message as an input.
The general syntax is:
assert(expression)
A custom error message can also be displayed if the assertion condition evaluates to be false.
assert expression, message
The following flow chart explains the concept:
The following code explains how to use the assert
in python:
x="Python Programming"assert(x=="Python Programming") # no errorassert(x=="Python Language") # Assertion error
The following example uses assert with a custom error message defined:
Note: When writing a custom message, do not put a bracket around the assert condition
assert False, "We've got a problem" #custom error messageassert 2 + 2 == 5, "We've got a problem" #custom error message
Free Resources