Python - Assert Statement

In Python, the assert statement is used to continue the execute if the given condition evaluates to True. If the assert condition evaluates to False, then it raises the AssertionError exception with the specified error message.

Syntax

assert condition [, Error Message] 

The following example demonstrates a simple assert statement.

Example: assert
x = 10
assert x > 0
print('x is a positive number.')
Output
x is a positive number.

In the above example, the assert condition, x > 0 evalutes to be True, so it will continue to execute the next statement without any error.

The assert statement can optionally include an error message string, which gets displayed along with the AssertionError. Consider the following assert statement with the error message.

Example: Assert Statement with Error Message
x = 0
assert x > 0, 'Only positive numbers are allowed'
print('x is a positive number.')
Output
Traceback (most recent call last):
    assert x > 0, 'Only positive numbers are allowed'
AssertionError: Only positive numbers are allowed

Above, x=0, so the assert condition x > 0 becomes False, and so it will raise the AssertionError with the specified message 'Only positive numbers are allowed'. It does not execute print('x is a positive number.') statement.

The following example uses the assert statement in the function.

Example: assert
def square(x):
    assert x>=0, 'Only positive numbers are allowed'
    return x*x

n = square(2) # returns 4
n = square(-2) # raise an AssertionError
Output
Traceback (most recent call last):
    assert x > 0, 'Only positive numbers are allowed'
AssertionError: Only positive numbers are allowed

Above, square(2) will return 4, whereas square(-2) will raise an AssertionError because we passed -2.

The AssertionError is also a built-in exception that can be handled using try-except construct as shown below:

Example: AssertionError
def square(x):
    assert x>=0, 'Only positive numbers are allowed'
    return x*x

try:
    square(-2)
except AssertionError as msg:
    print(msg)
Output
Only positive numbers are allowed

Above, calling square(-2) will raise an AssertionError, which will be handled by the except block. The error message in the assert statement will be passed as an argument to the exception argument msg, using as keyword.

Thus, the assert statement should generally be used to prevent possible errors and specify appropriate error messages.

Learn Python using coding questions with answers.

Python Questions & Answers

Want to check how much you know Python?

Start Python Skill Test