Python Tutorial Python Advanced Python References Python Libraries

Python assert Keyword



The Python assert keyword is used when debugging code. The assert keyword lets a user test a condition in the code. If the condition returns True the program will execute the next line of code and if the condition returns False the program will raise an AssertionError. A user can define the message to be returned if the condition returns false. See the example below:

Example:

In the example below, Python assert keyword checks whether the variable called TestVariable is 25 or not which is true and the program will run the next line of code. In the second part, the assert keyword again checks the value of TestVariable for 30 and returns false. This will raise an AssertionError exception.

TestVariable = 25
assert TestVariable == 25
print('Hello World!.')
TestVariable = TestVariable + 10

assert TestVariable == 30
print('Hello World!.')

The output of the above code will be:

Hello World!.

Traceback (most recent call last):
  File "Main.py", line 6, in <module>
    assert TestVariable == 30
AssertionError

A user can also define the message to be returned if the condition returns false.

TestVariable = 25
assert TestVariable == 30 , 'TestVariable should be 30.'
print('Hello World!.')

The output of the above code will be:

Traceback (most recent call last):
  File "Main.py", line 2, in <module>
    assert TestVariable == 30 , 'TestVariable should be 30.'
AssertionError: TestVariable should be 30.

❮ Python Keywords