溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

在Python中使用assert的作用是什么

發(fā)布時間:2021-05-08 15:31:33 來源:億速云 閱讀:233 作者:小新 欄目:編程語言

這篇文章主要介紹在Python中使用assert的作用是什么,文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!

python的數(shù)據(jù)類型有哪些?

python的數(shù)據(jù)類型:1. 數(shù)字類型,包括int(整型)、long(長整型)和float(浮點型)。2.字符串,分別是str類型和unicode類型。3.布爾型,Python布爾類型也是用于邏輯運算,有兩個值:True(真)和False(假)。4.列表,列表是Python中使用最頻繁的數(shù)據(jù)類型,集合中可以放任何數(shù)據(jù)類型。5. 元組,元組用”()”標(biāo)識,內(nèi)部元素用逗號隔開。6. 字典,字典是一種鍵值對的集合。7. 集合,集合是一個無序的、不重復(fù)的數(shù)據(jù)組合。

#1樓

斷言語句有兩種形式。

簡單的形式, assert <expression> ,相當(dāng)于

if __debug__:
    if not <expression>: raise AssertionError

擴(kuò)展形式assert <expression1>, <expression2>等同于

if __debug__:
    if not <expression1>: raise AssertionError, <expression2>

#2樓

這是一個簡單的例子,將其保存在文件中(假設(shè)為b.py)

def chkassert(num):
    assert type(num) == int
chkassert('a')

$python b.py時的結(jié)果

Traceback (most recent call last):  File "b.py", line 5, in <module>
    chkassert('a')  File "b.py", line 2, in chkassert
    assert type(num) == intAssertionError

#3樓

斷言是一種系統(tǒng)的方法,用于檢查程序的內(nèi)部狀態(tài)是否與程序員預(yù)期的一樣,目的是捕獲錯誤。 請參閱下面的示例。

>>> number = input('Enter a positive number:')
Enter a positive number:-1>>> assert (number > 0), 'Only positive numbers are allowed!'Traceback (most recent call last):
  File "<stdin>", line 1, in <module>AssertionError: Only positive numbers are allowed!>>>

#4樓

如果assert之后的語句為true,則程序繼續(xù),但如果assert之后的語句為false,則程序會給出錯誤。 就那么簡單。

例如:

assert 1>0   #normal executionassert 0>1   #Traceback (most recent call last):
             #File "<pyshell#11>", line 1, in <module>
             #assert 0>1
             #AssertionError

#5樓

format:assert Expression [,arguments]當(dāng)assert遇到一個語句時,Python會計算表達(dá)式。如果該語句不為true,則引發(fā)異常(assertionError)。 如果斷言失敗,Python使用ArgumentExpression作為AssertionError的參數(shù)。 可以使用try-except語句像任何其他異常一樣捕獲和處理AssertionError異常,但如果不處理,它們將終止程序并產(chǎn)生回溯。 例:

def KelvinToFahrenheit(Temperature):    
    assert (Temperature >= 0),"Colder than absolute zero!"    
    return ((Temperature-273)*1.8)+32    print KelvinToFahrenheit(273)    
print int(KelvinToFahrenheit(505.78))    
print KelvinToFahrenheit(-5)

執(zhí)行上面的代碼時,會產(chǎn)生以下結(jié)果:

32.0
451
Traceback (most recent call last):    
  File "test.py", line 9, in <module>    
    print KelvinToFahrenheit(-5)    
  File "test.py", line 4, in KelvinToFahrenheit    
    assert (Temperature >= 0),"Colder than absolute zero!"    AssertionError: Colder than absolute zero!

以上是“在Python中使用assert的作用是什么”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI