首页 > 编程语言 > 详细

python assert

时间:2018-08-28 16:59:15      阅读:199      评论:0      收藏:0      [点我收藏+]
assert(断言):

assert condition

assert 可以作为判断,在结果为True时什么都不返回,在结果为False时会触发一个错误,它等价于下面的判断

if not condition:
? ? raise AssertionError()

测试下:

\>>> assert True # nothing happens
assert False
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
\>>>

assert还可以包含一个额外的错误消息选项,如下面

\>\>\> assert False, ‘这是一个错误‘
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: 这是一个错误
\>>>
\>>> assert 1==2,(‘%s, 1不等于%d‘ % (‘hello‘, 2))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: hello, 1不等于2
\>>>

python assert

原文:http://blog.51cto.com/superzhangqiang/2165504

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!