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


当前回答

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

其他回答

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

在Python中,断言的目标是通知开发人员程序中不可恢复的错误。

断言并不是为了表明预期的错误条件,比如“文件未找到”,用户可以采取纠正措施(或者只是重试)。

另一种看待它的方法是,断言是代码中的内部自检。它们通过在代码中声明一些不可能的条件来工作。如果这些条件不成立,则意味着程序中存在错误。

如果您的程序没有错误,这些情况将永远不会发生。但如果其中一个确实发生了,程序将崩溃,并提示一个断言错误,告诉您究竟触发了哪个“不可能”条件。这使得跟踪和修复程序中的错误变得更加容易。

以下是我写的Python断言教程的摘要:

Python的assert语句是一种调试辅助,而不是处理运行时错误的机制。使用断言的目标是让开发人员更快地找到错误的可能根源。除非程序中存在错误,否则绝不应引发断言错误。

>>>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会引发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!
>>>