日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
Pythonassert語(yǔ)句

在 Python 中,如果給定條件評(píng)估為真,則使用assert語(yǔ)句繼續(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è)簡(jiǎn)單的 assert 語(yǔ)句。

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í)行下一條語(yǔ)句,沒(méi)有任何錯(cuò)誤。

assert 語(yǔ)句可以選擇性地包含一個(gè)錯(cuò)誤消息字符串,該字符串與AssertionError一起顯示。 考慮以下帶有錯(cuò)誤消息的assert語(yǔ)句。

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ù)”來(lái)引發(fā)AssertionError。 不執(zhí)行print('x is a positive number.')語(yǔ)句。

下面的示例在函數(shù)中使用了 assert 語(yǔ)句。

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)槲覀兺ㄟ^(guò)了-2。

AssertionError也是一個(gè)內(nèi)置的異常,可以使用 try 來(lái)處理-除了如下所示的構(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 語(yǔ)句中的錯(cuò)誤消息將作為參數(shù)傳遞給異常參數(shù)msg,使用as關(guān)鍵字。

因此,assert 語(yǔ)句通常應(yīng)該用于防止可能的錯(cuò)誤,并指定適當(dāng)?shù)腻e(cuò)誤消息。****


本文題目:Pythonassert語(yǔ)句
鏈接地址:http://m.5511xx.com/article/cccpooj.html