Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

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

I have a code and I want to test it and debug it.

x,y = 4,7
x>y

Is there any built-in function or statement in python to test code without using exception handling?


1 Answer
Manogna

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
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.