What is the use of "assert" statement in Python?

PythonServer Side ProgrammingProgramming

The assert statement has the following syntax.

assert <some_test>, <message>

The line above is read as: If <some_test> evaluates to False, an exception is raised and <message> will be output.

If we want to test some code block or an expression we put it after an assert keyword. If the test passes or the expression evaluates to true nothing happens. But if the test fails or the expression evaluates to false, an AssertionError is raised and the message is printed out or evaluated.

Assert statement is used for catching/testing user-defined constraints. It is used for debugging code and is inserted at the start of a script.

It is not used for catching code errors like x / 0, because Python catches such errors itself.

Given code can be tested using assert statement as follows:

x,y = 4,7
assert x > y, "x has to be smaller than y"

OUTPUT

Traceback (most recent call last):
File "C:/Users/TutorialsPoint1/~assert2.py", line 2, in <module>
assert x > y, "x has to be smaller than y"
AssertionError: x has to be smaller than y
raja
Published on 07-Dec-2017 11:10:52
Advertisements