断言是什么意思?它是如何使用的?


当前回答

格式: 断言表达式(参数) 当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 <expression>相当于

if __​debug__:
    if not <expression>: raise AssertionError

扩展形式assert <expression1>, <expression2>等价于

if __​debug__:
    if not <expression1>: raise AssertionError(<expression2>)
>>>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
>>> 

Python assert基本上是一种调试辅助工具,用于测试代码内部自检的条件。 当代码进入不可能的边缘情况时,Assert使调试变得非常容易。断言检查那些不可能的情况。

假设有一个函数计算商品折扣后的价格:

def calculate_discount(price, discount):
    discounted_price = price - [discount*price]
    assert 0 <= discounted_price <= price
    return discounted_price

这里,discounted_price永远不能小于0并且大于实际价格。因此,如果上述条件被违反,assert将引发断言错误,这有助于开发人员识别发生了不可能的事情。

希望能有所帮助。

注意括号。正如在其他回答中指出的那样,在Python 3中,assert仍然是一个语句,因此通过与print(..)类比,可以推断出assert(..)或raise(..),但不应该这样做。

这是错误的:

assert(2 + 2 == 5, "Houston we've got a problem")

这是正确的:

assert 2 + 2 == 5, "Houston we've got a problem"

第一个不能工作的原因是bool((False,“Houston we've got a problem”))的值为True。

在assert(False)语句中,这些只是在False周围的多余圆括号,对其内容求值。但是使用assert(False),圆括号现在是一个元组,而非空元组在布尔上下文中的计算结果为True。

断言是在我们的程序中自信地陈述事实的语句。

语法: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

重点:

它被用作调试工具。 它接受一个表达式和一个可选消息。 它几乎存在于每一种编程语言中