Assertions in Python

An assertion in Python is a way you use to test an expression so you can raise and exception if it is false. In this situation the assert statement is used.

Example:

print(1)
assert 2 + 2 == 4
print(2)
assert 1 + 1 == 3
print(3)

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
1
2
Traceback (most recent call last):
  File "file.py", line 4, in 
    assert 1 + 1 == 3
AssertionError
ddn_ro@linux:~/Desktop$

It prints 1, then it prints 2, but when it gets to line 4 we get an assertionError because 1+1 does not equal 3, so the print(3) won’t be executed.

Note:
Programmers often place assertions at the start of a function to check for valid input, and after a function call to check for valid output.

The assert can take a second argument that is passed to the AssertionError raised if the assertion fails.

Example:

temp = -1
assert (temp >= 0), "It’s not cold!”

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
Traceback (most recent call last):
  File "file.py", line 2, in 
    assert (temp >= 0), "It's not cold!"
AssertionError: It's not cold!
ddn_ro@linux:~/Desktop$

Note:
AssertionError exceptions can be caught and handled like any other exception using the try-except statement, but if not handled, this type of exception will terminate the program.

Leave a Reply