断言是什么意思?它是如何使用的?
当前回答
>>>this_is_very_complex_function_result = 9
>>>c = this_is_very_complex_function_result
>>>test_us = (c < 4)
>>> #first we try without assert
>>>if test_us == True:
print("YES! I am right!")
else:
print("I am Wrong, but the program still RUNS!")
I am Wrong, but the program still RUNS!
>>> #now we try with assert
>>> assert test_us
Traceback (most recent call last):
File "<pyshell#52>", line 1, in <module>
assert test_us
AssertionError
>>>
其他回答
正如其他答案所指出的,assert类似于在给定条件不为真时抛出异常。一个重要的区别是,如果使用优化选项-O编译代码,断言语句将被忽略。文档说断言表达式可以更好地描述为等效于
if __debug__:
if not expression: raise AssertionError
如果你想彻底测试你的代码,然后在你高兴地看到你的断言案例都没有失败时发布一个优化版本,这可能是有用的——当优化打开时,__debug__变量变成False,条件将停止计算。如果您依赖断言,而没有意识到断言已经消失,该特性还可以发现这一点。
格式: 断言表达式(参数) 当assert遇到语句时,Python对表达式求值。如果语句不为真,则引发异常(assertionError)。 如果断言失败,Python使用ArgumentExpression作为AssertionError的参数。可以像使用try-except语句一样捕获和处理AssertionError异常,但如果没有处理,它们将终止程序并产生跟踪。 例子:
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)
当执行上面的代码时,它会产生以下结果:
32.0
451
Traceback (most recent call last):
File "test.py", line 9, in <module>
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!"
AssertionError: Colder than absolute zero!
断言是在我们的程序中自信地陈述事实的语句。
语法:assert <条件>或assert <条件>,<错误消息>
它有一个条件/表达式,它应该总是为真。如果条件为false, assert语句将停止程序并抛出AssertionError错误消息。你的断言表达式将是你不希望在程序中出现的东西。
e.g.
Assert <条件>——使用Assert而没有<错误消息> var = int(输入("输入值1-9包含:")) 断言var != 0 打印(var) 输出: 如果输入为0: AssertionError 如果输入为1: 1 断言<条件>,<错误消息>——使用带有<错误消息>的断言 var = int(输入("输入值1-9包含:")) 断言var !=0,"输入不能为零" 打印(var) 输出: 如果输入为0: AssertionError:输入不能为零 如果输入为1: 1
重点:
它被用作调试工具。 它接受一个表达式和一个可选消息。 它几乎存在于每一种编程语言中
从文档:
断言语句是向程序中插入调试断言的一种方便方法
你可以在这里阅读更多:http://docs.python.org/release/2.5.2/ref/assert.html
这是一个简单的例子,保存到文件(比如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
推荐文章
- 得到熊猫栏目的总数
- 从pandas DataFrame中删除名称包含特定字符串的列
- Mock vs MagicMock
- 如何阅读一个。xlsx文件使用熊猫库在iPython?
- 如何访问熊猫组由数据帧按键
- Pandas和NumPy+SciPy在Python中的区别是什么?
- 将列表转换为集合会改变元素的顺序
- 如何在matplotlib更新一个情节
- TypeError: ` NoneType `对象在Python中不可迭代
- 'throw'和'throw new Exception()'的区别
- 如何在Vim注释掉一个Python代码块
- python标准库中的装饰符(特别是@deprecated)
- 如何从外部访问本地Django web服务器
- 删除字符串的最后3个字符
- 在python中执行no-op的标准方法是什么?