assert Statement in Python is useful to check if the given condition is true or not.
Flowchart

If the assert condition is true, the control simply moves to the next line of code. In case if it is false, then program terminates and returns AssertionError Exception.
As per Python documentation,
exception AssertionError is raised when an assert statement fails.
We can actually handle the AssertionError exception using try-except block in Python.
Syntax
assert expression, message
In the above syntax, message is an optional field.
Let us understand the working of assert function using some examples
Program : To take only even number as an input, Raise an Exception “Odd Integers are not allowed !”, if input value is odd. If number is even, print square of it.
n = int(input())
assert n%2==0, "Odd Integers are not allowed !"
print("Square of {0} is {1}".format(n, n*n))
Let’s test this code for two testcases :
Testcase 1 : I/P : 6
In this case, assert condition becomes true, hence, Square of the number is printed on the output screen.

Testcase 2 : I/P : 7
In this case, assert condition becomes false, hence, AssertionError is raised.

Application of assert Statement
- assert Statement in Python is used for unit testing to test various testcases of the program.
- assert Statement in Python is used to check the output of the program.
Well, that’s all about assert statement in Python.
