Python ASSERT Keyword

Python assert

Python assert keyword is used to check if a given condition is True, else raise an AssertionError.

Syntax – Python assert

The syntax to use Python assert keyword is

assert <expression>, [argument]

where

ParameterDescription
expression[mandatory] This expression will be evaluated to a boolean value.
argument[optional] This argument is passed to the exception raised.

assert throws AssertionError if expression evaluates to False.

Example 1: assert

In this example, we will use assert keyword to assert if a given string is equal to “Hello”.

Python Program

x = "hello"
assert x == "hello"
print('Done!')
Run

Output

Done!

Since the expression evaluates to True, assert does not raise any Error and continues with the next statements in the program.

Example 2: assert – Expression is False

In this example, we will use assert keyword to assert if a given string is equal to “Hello”. We will the string such that the expression evaluates to False. Since the expression is False, assert raises AssertionError.

Python Program

x = "hola"
assert x == "hello"
print('Done!')
Run

Output

Traceback (most recent call last):
  File "d:/workspace/python/example.py", line 2, in <module>
    assert x == "hello"
AssertionError

Example 3: assert – with Optional Argument

In this example, we will use assert keyword with an expression that evaluates to False and also pass the optional argument.

Python Program

x = "hola"
assert x == "hello", 'The two strings do not match.'
print('Done!')
Run

Output

Traceback (most recent call last):
  File "d:/workspace/python/example.py", line 2, in <module>
    assert x == "hello", 'The two strings do not match.'
AssertionError: The two strings do not match.

Please observe in the output, the argument is printed to the console AssertionError: The two strings do not match..

The optional argument is used only when the expression evaluates to False. If the expression evaluates to True, the argument is not used.

Summary

In this tutorial of Python Examples, we learned how to use Python assert keyword to debug our Python program, with the help of examples.