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 are assertions in Python and how are they carried out?

I want to test the following code both with and without using assert statement

(x,y) = (8, 8)
z = x < y

How can I raise AssertionError for the same code?


1 Answer
Rajendra Dharmkar

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

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

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
Advertisements

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