新聞中心
在 Python 中,如果給定條件評(píng)估為真,則使用assert語句繼續(xù)執(zhí)行。 如果斷言條件評(píng)估為假,那么它會(huì)引發(fā)帶有指定錯(cuò)誤消息的AssertionError異常。

創(chuàng)新互聯(lián)專業(yè)IDC數(shù)據(jù)服務(wù)器托管提供商,專業(yè)提供成都服務(wù)器托管,服務(wù)器租用,雅安電信機(jī)房,雅安電信機(jī)房,成都多線服務(wù)器托管等服務(wù)器托管服務(wù)。
句法
assert condition [, Error Message] 下面的示例演示了一個(gè)簡單的 assert 語句。
Example: assert
x = 10
assert x > 0
print('x is a positive number.') Output
x is a positive number. 在上面的例子中,斷言條件x > 0評(píng)估為真,因此它將繼續(xù)執(zhí)行下一條語句,沒有任何錯(cuò)誤。
assert 語句可以選擇性地包含一個(gè)錯(cuò)誤消息字符串,該字符串與AssertionError一起顯示。 考慮以下帶有錯(cuò)誤消息的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變?yōu)榧伲运鼤?huì)用指定的消息“只允許正數(shù)”來引發(fā)AssertionError。 不執(zhí)行print('x is a positive number.')語句。
下面的示例在函數(shù)中使用了 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)將加注一個(gè)AssertionError,因?yàn)槲覀兺ㄟ^了-2。
AssertionError也是一個(gè)內(nèi)置的異常,可以使用 try 來處理-除了如下所示的構(gòu)造:
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 上圖,調(diào)用square(-2)會(huì)引發(fā)AssertionError,由除塊處理。 assert 語句中的錯(cuò)誤消息將作為參數(shù)傳遞給異常參數(shù)msg,使用as關(guān)鍵字。
因此,assert 語句通常應(yīng)該用于防止可能的錯(cuò)誤,并指定適當(dāng)?shù)腻e(cuò)誤消息。****
標(biāo)題名稱:Pythonassert語句
URL分享:http://m.fisionsoft.com.cn/article/cccpooj.html


咨詢
建站咨詢
