1.

What is assert in Python? Is it a function, class or keyword? Where and how is it used?

Answer»

‘assert’ is one of 33 KEYWORDS in Python LANGUAGE. Essentially it CHECKS whether given boolean expression is true. If expression is true, Python interpreter goes on to execute subsequent code. However, if the expression is false, AssertionError is raised bringing execution to halt.

To DEMONSTRATE usage of assert statement, let us consider following function:

>>> def testassert(x,y): assert y!=0 print ('division=',x/y)

Here, the division will be performed only if boolean condition is true, but AssertionError raised if it is false

>>> testassert(10,2) division= 5.0 >>> testassert(10,0) Traceback (most recent call last):  File "<pyshell#8>", line 1, in <module>    testassert(10,0)  File "<pyshell#6>", line 2, in testassert    assert y!=0 AssertionError

AssertionError is raised with a string in assert statement as custom error message

>>> def testassert(x,y): assert y!=0, 'Division by Zero not allowed' print ('division=',x/y) >>> testassert(10,0) Traceback (most recent call last):  File "<pyshell#11>", line 1, in <module>    testassert(10,0)  File "<pyshell#10>", line 2, in testassert    assert y!=0, 'Division by Zero not allowed' AssertionError: Division by Zero not allowed

Instead of letting the execution terminate abruptly, the AssertionError is handled with try – except construct as follows:

>>> def testassert(x,y): try: assert y!=0 print ('division', x/y) except AssertionError: print ('Division by Zero not allowed') >>> testassert(10,0) Division by Zero not allowed


Discussion

No Comment Found