Computer >> Computer tutorials >  >> Programming >> Python

What are assertions in Python and how are they carried out?


An assertion is a sanity-test when you are done with your testing of a program.

An assertion is similar to a raise-if statement (or to be more precise, a raise-if-not statement). An expression is tested, and if the result turns out to be false, an exception is raised. Assertions are carried out by using the assert statement.

Programmers often put assertions at the start of a function to check for valid input, and after a function call to check for valid output. Using assert statement below

Example

x,y = 8,8
assert x<y, 'x and y are equal'

Output

Traceback (most recent call last):
File "C:/Users/TutorialsPoint1/PycharmProjects/TProg/Exception
handling/assertionerror1.py", line 9, in <module>
assert x<y, 'x and y are equal'
AssertionError: x and y are equal

Equivalent code without assert statement producing same output is as follows

Example

x,y =8,8
if not x<y :
raise AssertionError('x and y are equal')

Output

Traceback (most recent call last):
File "C:/Users/TutorialsPoint1/PycharmProjects/TProg/Exception handling/assertionerror1.py", line 7, in <module>
raise AssertionError('x and y are equal')
AssertionError: x and y are equal