What does assert mean in Python?
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.
Syntax
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:
What can assertion do?
- It can check the type and value of the argument as well as the output of the function.
- It can be used as a debugging tool since it halts the program where the statements execute to be false.
Examples
1. Without a custom error message
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
2. With a custom error message
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