Easy Tutorial
❮ Python Os Listdir Python File Fileno ❯

Python3 assert (Assertion)

Python3 Errors and Exceptions

Python assert (assertion) is used to evaluate an expression, and it raises an exception when the condition is false.

Assertions can immediately return an error if the conditions are not met, preventing the program from running into a crash later on. For example, if our code is intended to run only on Linux systems, we can check if the current system meets the condition beforehand.

The syntax is as follows:

assert expression

This is equivalent to:

if not expression:
    raise AssertionError

assert can also be followed by parameters:

assert expression [, arguments]

This is equivalent to:

if not expression:
    raise AssertionError(arguments)

Here are examples of using assert:

>>> assert True     # Condition is true, executes normally
>>> assert False    # Condition is false, raises an exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError
>>> assert 1==1     # Condition is true, executes normally
>>> assert 1==2     # Condition is false, raises an exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

>>> assert 1==2, '1 is not equal to 2'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError: 1 is not equal to 2
>>>

The following example checks if the current system is Linux, and if not, it raises an exception immediately without executing subsequent code:

Example

import sys
assert ('linux' in sys.platform), "This code can only be executed on Linux"

# Code to be executed next

Python3 Errors and Exceptions

❮ Python Os Listdir Python File Fileno ❯