assert statement


Assert statements are used when debugging code. It has a condition which is supported to be always True. If the condition is False then assert halts the program and gives ad AssertionError.

Syntax for using Assert:

assert <condition>
assert <condition>, <error message>

Error message is an optional in assert statement which can give custom error message along with AssertionError.

For example:

Without Error Message

def average(arg):
    assert len(arg) != 0
    return sum(arg)/len(arg)

lst = []
print(average(lst))

The output will be:

AssertionError

With Error Message

def average(arg):
    assert len(arg) != 0, 'List is empty.'
    return sum(arg)/len(arg)

lst = []
print(average(lst))

The output will be:

AssertionError: List is empty


See also: