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


当前回答

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