python assert用法

来源:互联网 发布:linux 命令行支持中文 编辑:程序博客网 时间:2024/06/15 11:54

http://blog.sina.com.cn/s/blog_76e94d210100vz37.html

http://www.cnblogs.com/cedrelaliu/p/5948567.html

http://www.cnblogs.com/liuchunxiao83/p/5298016.html


1、assert语句用来声明某个条件是真的。
2、如果你非常确信某个你使用的列表中至少有一个元素,而你想要检验这一点,并且在它非真的时候引发一个错误,那么assert语句是应用在这种情形下的理想语句。
3、当assert语句失败的时候,会引发一AssertionError

测试程序:
>>> mylist =['item']
>>> assertlen(mylist) >= 1
>>>mylist.pop()
'item'
>>> assertlen(mylist) >= 1
Traceback (most recent call last):
  File"<stdin>", line 1, in<module>
AssertionError
>>>


python assert的作用

使用assert断言是学习python一个非常好的习惯,python assert 断言句语格式及用法很简单。在没完善一个程序之前,我们不知道程序在哪里会出错,与其让它在运行最崩溃,不如在出现错误条件时就崩溃,这时候就需要assert断言的帮助。本文主要是讲assert断言的基础知识。

python assert断言的作用

python assert断言是声明其布尔值必须为真的判定,如果发生异常就说明表达示为假。可以理解assert断言语句为raise-if-not,用来测试表示式,其返回值为假,就会触发异常。

assert断言语句的语法格式


assert python 怎么用?
expression assert 表达式

下面做一些assert用法的语句供参考:
assert 1==1
assert 2+2==2*2
assert len(['my boy',12])<10
assert range(4)==[0,1,2,3]

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

assert的异常参数,其实就是在断言表达式后添加字符串信息,用来解释断言并更好的知道是哪里出了问题。格式如下:
assert expression [, arguments]
assert 表达式 [, 参数]

assert len(lists) >=5,'列表元素个数小于5'
assert 2==1,'2不等于1'



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".

 

一般的用法是:

assert condition

用来让程序测试这个condition,如果condition为false,那么raise一个AssertionError出来。逻辑上等同于:

if not condition:    raise AssertionError()

比如如下的例子:

复制代码
>>> assert 1==1>>> assert 1==0Traceback (most recent call last):  File "<pyshell#1>", line 1, in <module>    assert 1==0AssertionError>>> assert True>>> assert FalseTraceback (most recent call last):  File "<pyshell#3>", line 1, in <module>    assert FalseAssertionError>>> assert 3<2Traceback (most recent call last):  File "<pyshell#4>", line 1, in <module>    assert 3<2AssertionError
复制代码