python中的assert用法

 参考官方文档:https://docs.python.org/3/reference/simple_stmts.html#assert

7.3. The assert statement

Assert statements are a convenient way to insert debugging assertions into a program:

# 断言语句是向程序插入调试断言的一种方便方法:

assert_stmt ::=  "assert" expression ["," expression]

The simple form, assert expression, is equivalent to

if __debug__:
    if not expression: raise AssertionError

The extended form, assert expression1, expression2, is equivalent to

if __debug__:
    if not expression1: raise AssertionError(expression2)

These equivalences assume that __debug__ and AssertionError refer to the built-in variables with those names. In the current implementation, the built-in variable __debug__ is True under normal circumstances, False when optimization is requested (command line option -O). The current code generator emits no code for an assert statement when optimization is requested at compile time. Note that it is unnecessary to include the source code for the expression that failed in the error message; it will be displayed as part of the stack trace.

Assignments to __debug__ are illegal. The value for the built-in variable is determined when the interpreter starts.

assert使用其实类似于一个assert confition判断内容是否为真,如果为真,则执行跳过,如果为假则抛出错误,同时可以在判断语句后添加提示语句,帮助我们进行错误的定位;

实例如:

>>> assert 2 > 3, '2大于3错误'           
Traceback (most recent call last):   
  File "<stdin>", line 1, in <module>
AssertionError: 2大于3错误               
>>> assert 2 < 3, '2小于3正确'           
>>>                                  

上述实例中,当我们的语句或表达式判断为真,那么直接跳过,如果判断为假,输出错误提示信息,帮我们进行错误定位

>>> assert True

>>> assert False
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError   
   
>>> assert False, '条件为假,所以抛出本条错误信息'
Traceback (most recent call last): 
  File "<stdin>", line 1, in <modul
AssertionError: 条件为假,所以抛出本条错误信息    
>>>                                

猜你喜欢

转载自blog.csdn.net/qq_32670879/article/details/82343889