Python : Assert Keyword

Python’s assert keyword to check if a condition returns true or not. If it returns False, the execution of the program is to terminate and throw an AssertionError. And if the condition become True, then nothing happens.

Example 1- 

Here, we have checked in division function that the denominator must be greater than 0. If the condition fails, python interpreter raises an AssertionError.

def division_fn(x,y):
    assert y > 0, 'y should be positive number'
    print("Division is :",x/y)	

division_fn(12,6)           # condition become True, work perfectly fine
division_fn(12,0)           # condition become False, raise an AssertionError
# Output
Division is : 2.0                      # Output of division_fn(12,6)

Traceback (most recent call last):     # Output of division_fn(12,0)
  File "arg.py", line 6, in <module>
    divi_fn(12,0)
  File "arg.py", line 2, in divi_fn
    assert y > 0, 'y should be positive number'
AssertionError: y should be positive number

Example 2 –

x = "apple"
assert x == "banana", 'x should be apple'
# Output
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-29-aea68b4ac1f5> in <module>()
      1 x = "apple"
----> 2 assert x == "banana", 'x should be apple'

AssertionError: x should be apple

.     .     .

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Tutorials

Python – List Comprehension

Python Set

Python Dictionary

Python Tuple

Python List

Python: String

Python: String Formatting using f-string

Python: String Formatting – 2

Python: String Formatting – 1

Python Input/Output

Python Type Conversion and Type Casting

Python Comments

Python – Regular Expression (RegEx)

Python Iterators

Python File Handling

Python Exceptions

Python Function

Python Loops

Python If…Else

Python Collections

Python Operators

Variables in Python

Python Syntax

Introduction to Python

Python OOPs Concepts