用来检查,过程变量在代码运行过程中是不是和期望一样,若不是的话,则程序终止
>>> a=-1
>>> assert a<0
>>> assert a>0
Traceback (most recent call last):
File "" , line 1, in <module>
assert a>0
AssertionError
因为a=-1,当assert a<0
时,期望的a满足小于0,所以没报错;当assert a>0
时,a大于0,所以报错
可以加逗号在后面附上报错输出语:
>>> a=-1
>>> assert a>0, '{} is not in the correct range.'.format(a)
Traceback (most recent call last):
File "" , line 1, in <module>
assert a>0, '{} is not in the correct range.'.format(a)
AssertionError: -1 is not in the correct range.
{}
指向的是后面的.format(a)
的内容,输出里面顺利提示AssertionError: -1 is not in the correct range.
,之前AssertionError
后面是没有提示的(可以看上面)