断言是什么意思?它是如何使用的?
当前回答
如果assert后的语句为真,则程序继续执行,但如果assert后的语句为假,则程序报错。就这么简单。
例如:
assert 1>0 #normal execution
assert 0>1 #Traceback (most recent call last):
#File "<pyshell#11>", line 1, in <module>
#assert 0>1
#AssertionError
其他回答
如果assert关键字后面的代码为False, Python中的assert关键字将引发AssertionError。如果没有,它继续什么都没有发生。
示例1:
a = 5
b = 6
assert a == b
输出:
AssertionError
这是因为,很明显,a不等于b。 如果你想在代码中引发一个异常,这是特别有用的。
def get_dict_key(d, k):
try:
assert k in d
return d[k]
except Exception:
print("Key must be in dict.")
上面的示例实际上是无用的,但是请记住,它主要用于调试目的,因此您可以跟踪错误。
如果assert后的语句为真,则程序继续执行,但如果assert后的语句为假,则程序报错。就这么简单。
例如:
assert 1>0 #normal execution
assert 0>1 #Traceback (most recent call last):
#File "<pyshell#11>", line 1, in <module>
#assert 0>1
#AssertionError
断言是一种系统的方法,用于检查程序的内部状态是否如程序员所期望的那样,目的是捕捉错误。请参阅下面的示例。
>>> number = input('Enter a positive number:')
Enter a positive number:-1
>>> assert (number > 0), 'Only positive numbers are allowed!'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: Only positive numbers are allowed!
>>>
这是一个简单的例子,保存到文件(比如b.py)
def chkassert(num):
assert type(num) == int
chkassert('a')
当$python b.py
Traceback (most recent call last):
File "b.py", line 5, in <module>
chkassert('a')
File "b.py", line 2, in chkassert
assert type(num) == int
AssertionError
从文档:
断言语句是向程序中插入调试断言的一种方便方法
你可以在这里阅读更多:http://docs.python.org/release/2.5.2/ref/assert.html
推荐文章
- 我如何让红宝石打印一个完整的回溯而不是截断一个?
- Visual Studio:如何打破处理异常?
- 如何在Flask-SQLAlchemy中按id删除记录
- 在Python中插入列表的第一个位置
- Python Pandas只合并某些列
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?
- 使用Python请求的异步请求
- 无法加载文件或程序集…参数不正确
- 如何检查一个对象是否是python中的生成器对象?