【Python】assert()断言简单用法

版权声明:本文为博主原创文章,转载时附上原文链接即可 https://blog.csdn.net/weixin_38705903/article/details/88563475

用来检查,过程变量在代码运行过程中是不是和期望一样,若不是的话,则程序终止

>>> a=-1
>>> assert a<0
>>> assert a>0
Traceback (most recent call last):
  File "<pyshell#2>", 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 "<pyshell#9>", 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后面是没有提示的(可以看上面)

猜你喜欢

转载自blog.csdn.net/weixin_38705903/article/details/88563475