Assert is the meaning of assertion, which is interpreted as: I conclude that there will be such a result after or before the execution of this program. If it is not, then throw an error.
grammar:
assert expression [, arguments]
assert expression[, parameter]
**Example: **
def foo(s):
n =int(s)
assert n !=0,'n is zero!'return10/ n
def main():foo('0')Traceback(most recent call last):...
AssertionError: n is zero!
The meaning of assert is that the expression n != 0 should be True, otherwise, according to the logic of program operation, the following code will definitely go wrong.
If the assertion fails, the assert statement itself will throw an AssertionError:
You can use the -O parameter to turn off assert when starting the Python interpreter
Supplementary knowledge: assertion exception in python
The assert in python is the simplest exception mechanism
**The basic syntax of assert is: **
“assert” expression1 [“,” expression2]
expression1 is used to determine the generation of a Boolean value. When expression1 is false, an exception is thrown. The content in [] is optional, that is, the user can select the prompt value of the exception:
a=23
assert a==23
a=a-1
assert a==23Traceback(most recent call last):
File "<stdin ", line 1,in<module
AssertionError
assert a==23,"error1"Traceback(most recent call last):
File "<stdin ", line 1,in<module
AssertionError: error1
The above detailed explanation of python error handling assert is all the content shared by the editor. I hope to give you a reference.
Recommended Posts