The sentence format and usage of python assert are very simple. Usually the program throws an exception after it runs, and using assert can terminate the operation directly at the code where an exception occurs. Instead of waiting for an exception to be thrown after the program has been executed.
The role of python assert
If an exception occurs to python assert, the expression is false. It is understandable that an exception is triggered when the expression returns a false value.
The grammatical format of assert statements
assert expression [, arguments]
assert Expression [, parameter]
Additional note: assert can also be used for multiple expressions: assert expression 1, expression 2.
Note: When the expression = false, the following exception is executed.
Let's look at a few examples
1: Single expression:
a = 1 assert a < 0, 'Error,a More than 0.' print('There will be no output.')
Output:
Traceback (most recent call last): File "main.py", line 3, in <module> assert a < 0, 'Error,a More than 0.' AssertionError: Error,a More than 0.
2: Multiple expressions:
a = 1 b = -1 assert a > 0, b < 0 print('Normal output,The expression returns true') # Output: Normal Output,The expression returns true
3: Attempt to catch assert exceptions:
import traceback try: assert a < 0 except AssertionError as aeeor: # Clearly throw this exception # Throw out AssertionError It does not contain any information, so it cannot be passed. aeeor.__str__()Get exception description print('AssertionError', aeeor, aeeor.__str__()) # adopt traceback Print detailed exception information print('traceback Print exception') traceback.print_exc() except: # Will not hit other exceptions print('assert except') try: raise AssertionError('test raise AssertionError') except AssertionError as aeeor: print('raise AssertionError abnormal', aeeor.__str__())
Output:
1 AssertionError 2 traceback Print exception 3 Traceback (most recent call last): 4 File "main.py", line 7, in <module> 5 assert a < 0 6 AssertionError 7 raise AssertionError Abnormal testing raise AssertionError
4: Function calls throw exceptions:
# Division def foo(value, divide): assert divide != 0 return value / divide print('4 Divided by 2 =', foo(4, 2)) # Successful implementation print('4 Divided by 0 =', foo(4, 0)) # throw
Output:
1 4 Divided by 2 = 2.0 2 Traceback (most recent call last): 3 File "main.py", line 8, in <module> 4 print('4 Divided by 0 =', foo(4, 0)) # throw 5 File "main.py", line 3, in foo 6 assert divide != 0 7 AssertionError
Through the above examples, I believe you also have a deep understanding of the usefulness of aseert.
Summary: When the expression returns false. Throw an exception directly to terminate execution.