Skip to content

Python assert语句

更新:2022-07-24 09:58

在 Python 中,如果给定条件评估为真,则使用assert语句继续执行。 如果断言条件评估为假,那么它会引发带有指定错误消息的AssertionError异常。

句法

py
assert condition [, Error Message]

下面的示例演示了一个简单的 assert 语句。

Example: assert

py
x = 10
assert x > 0
print('x is a positive number.')

Output

py
x is a positive number.

在上面的例子中,断言条件x > 0评估为真,因此它将继续执行下一条语句,没有任何错误。

assert 语句可以选择性地包含一个错误消息字符串,该字符串与AssertionError一起显示。 考虑以下带有错误消息的assert语句。

Example: Assert Statement with Error Message

py
x = 0
assert x > 0, 'Only positive numbers are allowed'
print('x is a positive number.')

Output

py
Traceback (most recent call last):
    assert x > 0, 'Only positive numbers are allowed'
AssertionError: Only positive numbers are allowed

以上,x=0,所以断言条件x > 0变为假,所以它会用指定的消息“只允许正数”来引发AssertionError。 不执行print('x is a positive number.')语句。

下面的示例在函数中使用了 assert 语句。

Example: assert

py
def square(x):
    assert x>=0, 'Only positive numbers are allowed'
    return x*x

n = square(2) # returns 4
n = square(-2) # raise an AssertionError

Output

py
Traceback (most recent call last):
    assert x > 0, 'Only positive numbers are allowed'
AssertionError: Only positive numbers are allowed

上图中,square(2)将返回 4,而square(-2)将加注一个AssertionError,因为我们通过了-2。

AssertionError也是一个内置的异常,可以使用 try 来处理-除了如下所示的构造:

Example: AssertionError

py
def square(x):
    assert x>=0, 'Only positive numbers are allowed'
    return x*x

try:
    square(-2)
except AssertionError as msg:
    print(msg)

Output

py
Only positive numbers are allowed

上图,调用square(-2)会引发AssertionError,由除块处理。 assert 语句中的错误消息将作为参数传递给异常参数msg,使用as关键字。

因此,assert 语句通常应该用于防止可能的错误,并指定适当的错误消息。****