在 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 語句通常應該用於防止可能的錯誤,並指定適當的錯誤消息。****
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/271828.html
微信掃一掃
支付寶掃一掃