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


当前回答

注意括号。正如在其他回答中指出的那样,在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会引发AssertionError,否则只是继续代码,如果有逗号,无论它是什么,它都会在逗号后引发AssertionError: whatever,而to code则是:引发AssertionError(逗号后的whatever)

相关教程:

https://www.tutorialspoint.com/python/assertions_in_python.htm

断言是一种系统的方法,用于检查程序的内部状态是否如程序员所期望的那样,目的是捕捉错误。请参阅下面的示例。

>>> 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!
>>> 

从文档:

断言语句是向程序中插入调试断言的一种方便方法

你可以在这里阅读更多:http://docs.python.org/release/2.5.2/ref/assert.html

注意括号。正如在其他回答中指出的那样,在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。

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