在 Python 中,如果給定條件評估為真,則使用assert
語句繼續執行。 如果斷言條件評估為假,那么它會引發帶有指定錯誤消息的AssertionError
異常。
句法
assert condition [, Error Message]
下面的示例演示了一個簡單的 assert 語句。
Example: assert
x = 10
assert x > 0
print('x is a positive number.')
Output
x is a positive number.
在上面的例子中,斷言條件x > 0
評估為真,因此它將繼續執行下一條語句,沒有任何錯誤。
assert 語句可以選擇性地包含一個錯誤消息字符串,該字符串與AssertionError
一起顯示。 考慮以下帶有錯誤消息的assert
語句。
Example: Assert Statement with Error Message
x = 0
assert x > 0, 'Only positive numbers are allowed'
print('x is a positive number.')
Output
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
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
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
def square(x):
assert x>=0, 'Only positive numbers are allowed'
return x*x
try:
square(-2)
except AssertionError as msg:
print(msg)
Output
Only positive numbers are allowed
上圖,調用square(-2)
會引發AssertionError
,由除塊處理。 assert 語句中的錯誤消息將作為參數傳遞給異常參數msg
,使用as
關鍵字。
因此,assert 語句通常應該用于防止可能的錯誤,并指定適當的錯誤消息。****