一、python assert的作用:
根据Python 官方文档解释(https://docs.python.org/3/reference/simple_stmts.html#assert), "Assert statements are a convenient way to insert debugging assertions into a program".
二、一般的用法是:
1 assert condition 2 用来让程序测试这个condition,如果condition为false,那么raise一个AssertionError出来。逻辑上等同于: 3 4 if not condition: 5 raise AssertionError()
例如:
1 >>> assert 1==1 2 >>> assert 1==0 3 Traceback (most recent call last): 4 File "<pyshell#1>", line 1, in <module> 5 assert 1==0 6 AssertionError 7 >>> assert True 8 >>> assert False 9 Traceback (most recent call last): 10 File "<pyshell#3>", line 1, in <module> 11 assert False 12 AssertionError 13 >>> assert 3<2 14 Traceback (most recent call last): 15 File "<pyshell#4>", line 1, in <module> 16 assert 3<2 17 AssertionError
三、如何为assert断言语句添加异常参数
assert的异常参数,其实就是在断言表达式后添加字符串信息,用来解释断言并更好的知道是哪里出了问题。格式如下:
assert expression [, arguments]
assert 表达式 [, 参数]
例如:
1 >>> assert len(lists) >=5,'列表元素个数小于5' 2 Traceback (most recent call last): 3 File "D:/Data/Python/helloworld/helloworld.py", line 1, in <module> 4 assert 2>=5,'列表元素个数小于5' 5 AssertionError: 列表元素个数小于5 6 >>> assert 2==1,'2不等于1' 7 Traceback (most recent call last): 8 File "D:/Data/Python/helloworld/helloworld.py", line 1, in <module> 9 assert 2==1,'2不等于1' 10 AssertionError: 2不等于1