温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

assert语句怎么在Python中使用

发布时间:2021-03-24 16:01:07 来源:亿速云 阅读:129 作者:Leah 栏目:开发技术

本篇文章为大家展示了assert语句怎么在Python中使用,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

简单用法:

assert expression

让我们用程序来测试这个expression,如果expression相当于False,那么raise一个AssertionError出来。

即逻辑上等同于:

if not expression:
 raise AssertionError

简单看看这些例子:

>>> assert True
>>> assert False
Traceback (most recent call last):
 File "<pyshell#3>", line 1, in <module>
 assert False
AssertionError

>>> assert 1==1
>>> assert 1==0
Traceback (most recent call last):
 File "<pyshell#1>", line 1, in <module>
 assert 1==0
AssertionError

>>> assert [1, 2] # 非空列表值得注意一下,虽说也没个啥,哈哈
>>> assert not [1, 2]
Traceback (most recent call last):
 File "<ipython-input-48-eae410664122>", line 1, in <module>
 assert not [1, 2]
AssertionError

为assert断言语句添加异常参数

assert的异常参数,其实就是在断言表达式后添加字符串信息,一般用来解释断言。格式如下:

assert expression [, arguments]
assert 表达式 [, 参数]

举例请看之后的代码

一些重要的细节

老铁们可以试着运行一下以下代码段:

>>> assert None, 'None若作为布尔表达式,则相当于False'
>>> assert [], '空列表若作为布尔表达式,则相当于False'
>>> assert (), '空元组若作为布尔表达式,则相当于False'
>>> assert {}, '空字典若作为布尔表达式,则相当于False'
>>> assert set(), '空集合若作为布尔表达式,则相当于False'
>>> assert '', '空字符串若作为布尔表达式,则相当于False'

当然还有奇葩的numpy

>>> a = np.array([1, 2])
>>> assert a 
Traceback (most recent call last):

 File "<ipython-input-45-63e954d94e9b>", line 1, in <module>
 assert aa

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

是的,你没看错,哪里有numpy,哪里就有Use a.any() or a.all()......

最后,再试一试这俩吧:

>>> assert np.array([])
>>> assert np.array([[], []])

上述内容就是assert语句怎么在Python中使用,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI