YouTip LogoYouTip

Python3 Assert

# Python3 assert (Assertions) ## Python3.x Python3 assert (Assertions) [![Image 4: Document Object Reference](#) Python3 Errors and Exceptions](#) Python's `assert` statement is used to check an expression. If the condition of the expression is false, it triggers an exception. Assertions can directly return an error when a condition is not met during program execution, without waiting for the program to crash later. For example, if our code can only run on a Linux system, we can first check if the current system meets the requirement. !(#) The syntax is as follows: ```python assert expression This is equivalent to: ```python if not expression: raise AssertionError You can also follow `assert` with arguments: ```python assert expression [, arguments] This is equivalent to: ```python if not expression: raise AssertionError(arguments) Here are some examples of using `assert`: ```python >>> assert True # Condition is true, executes normally >>> assert False # Condition is false, triggers an exception Traceback (most recent call last): File "", line 1, in AssertionError >>> assert 1==1 # Condition is true, executes normally >>> assert 1==2 # Condition is false, triggers an exception Traceback (most recent call last): File "", line 1, in AssertionError >>> assert 1==2, '1 is not equal to 2' Traceback (most recent call last): File "", line 1, in AssertionError: 1 is not equal to 2 >>> The following example checks if the current system is Linux. If the condition is not met, it directly triggers an exception, so the subsequent code does not need to be executed: ## Example ```python import sys assert('linux' in sys.platform), "This code can only be executed on Linux" # Code to be executed next [![Image 6: Document Object Reference](#) Python3 Errors and Exceptions](#)
← Python3 Namespace ScopePostgresql Functions β†’