Python斷言assert是幫助代碼流暢的調(diào)試工具。斷言主要是假設(shè)程序員知道或總是希望是真的,因此將它們放在代碼中,這樣這些失敗不會允許代碼進(jìn)一步執(zhí)行。
簡單地說,斷言是一個布爾表達(dá)式,用來檢查語句是True還是False。如果語句為True,則不執(zhí)行任何操作并繼續(xù)執(zhí)行,但如果語句為False,則停止執(zhí)行程序并拋出錯誤。
Python assert語句流程圖
Python assert關(guān)鍵字語法
語法: assert condition, error_message(optional)
參數(shù):
condition:返回True或False的布爾值條件。
error_message:在AssertionError的情況下,在控制臺中打印的可選參數(shù)。
返回:AssertionError,如果條件計(jì)算為False。
在Python中,assert關(guān)鍵字有助于完成此任務(wù)。此語句接受一個布爾條件作為輸入,當(dāng)返回True時,不做任何事情并繼續(xù)正常的執(zhí)行流程,但如果計(jì)算結(jié)果為False,則引發(fā)AssertionError。
例如:
# initializing number
a = 4
b = 0
# using assert to check for 0
print("The value of a / b is : ")
assert b != 0
print(a / b)
輸出
The value of a / b is :
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
Input In [19], in <cell line: 10>()
8 # using assert to check for 0
9 print("The value of a / b is : ")
---> 10 assert b != 0
11 print(a / b)
AssertionError:
這段代碼試圖通過在執(zhí)行除法操作之前檢查b的值是否為0。a初始化為4,b初始化為0。程序打印消息a / b的值是:assert語句檢查b是否不等于0。由于b為0,assert語句失敗并引發(fā)AssertionError。
由于失敗的assert語句引發(fā)異常,程序終止,不再繼續(xù)執(zhí)行下一行的print語句。
帶有error_message參數(shù)的assert
a = 4
b = 0
# using assert to check for 0
print("The value of a / b is : ")
assert b != 0, "Zero Division Error"
print(a / b)
輸出
AssertionError: Zero Division Error
在函數(shù)內(nèi)部使用assert斷言
在本例中,assert語句用于函數(shù)內(nèi)部,以在計(jì)算矩形的面積之前驗(yàn)證矩形的長度和寬度是否為正。如果斷言為False,則會引發(fā)AssertionError,并顯示消息“Length and width must be positive”。如果斷言為True,則函數(shù)返回矩形的面積;如果為False,則退出并返回一個錯誤。為了展示如何在各種情況下使用assert,該函數(shù)被調(diào)用兩次,一次使用正輸入,一次使用負(fù)輸入。
def calculate_rectangle_area(length, width):
# Assertion to check that the length and width are positive
assert length > 0 and width > 0, "Length and width"+ \
"must be positive"
# Calculation of the area
area = length * width
# Return statement
return area
# Calling the function with positive inputs
area1 = calculate_rectangle_area(5, 6)
print("Area of rectangle with length 5 and width 6 is", area1)
# Calling the function with negative inputs
area2 = calculate_rectangle_area(-5, 6)
print("Area of rectangle with length -5 and width 6 is", area2)
帶有布爾值條件的斷言
在這個例子中,assert語句檢查布爾條件x < y是否為真。如果斷言失敗,則引發(fā)AssertionError。如果斷言通過,程序?qū)⒗^續(xù)并打印x和y的值。
# Initializing variables
x = 10
y = 20
# Asserting a boolean condition
assert x < y
# Printing the values of x and y
print("x =", x)
print("y =", y)
輸出
x = 10
y = 20
檢查變量類型的斷言
在本例中,assert語句檢查變量a和b的類型是否分別為str和int。如果任何斷言失敗,它將引發(fā)AssertionError。如果兩個斷言都通過,程序繼續(xù)并打印a和b的值。
# Initializing variables
a = "hello"
b = 42
# Asserting the type of a variable
assert type(a) == str
assert type(b) == int
# Printing the values of a and b
print("a =", a)
print("b =", b)
輸出
a = hello
b = 42
斷言字典的值
# Initializing a dictionary
my_dict = {"apple": 1, "banana": 2, "cherry": 3}
# Asserting the contents of the dictionary
assert my_dict["apple"] == 1
assert my_dict["banana"] == 2
assert my_dict["cherry"] == 3
# Printing the dictionary
print("My dictionary contains the following key-value pairs:", my_dict)
輸出
My dictionary contains the following key-value pairs:
{'apple': 1, 'banana': 2, 'cherry': 3}
實(shí)際應(yīng)用
這在任何開發(fā)領(lǐng)域的測試和質(zhì)量保證角色中都有更大的用處。根據(jù)應(yīng)用程序使用不同類型的斷言。下面是一個簡單的程序演示,該程序只允許調(diào)度所有熱食品的批次,否則拒絕整個批次。
# initializing list of foods temperatures
batch = [40, 26, 39, 30, 25, 21]
# initializing cut temperature
cut = 26
# using assert to check for temperature greater than cut
for i in batch:
assert i >= 26, "Batch is Rejected"
print (str(i) + " is O.K" )
輸出
40 is O.K
26 is O.K
39 is O.K
30 is O.K
運(yùn)行時異常:文章來源:http://www.zghlxwxcb.cn/news/detail-675133.html
AssertionError: Batch is Rejected
為什么要使用Python assert語句?
在Python中,assert語句是一個強(qiáng)大的調(diào)試工具,可以幫助識別錯誤并確保代碼按預(yù)期運(yùn)行。下面是使用assert的幾個理由:文章來源地址http://www.zghlxwxcb.cn/news/detail-675133.html
- 調(diào)試:代碼所做的假設(shè)可以用assert語句進(jìn)行驗(yàn)證。通過在整個代碼中放置assert語句,可以快速找到錯誤并調(diào)試程序。
- 文檔:在代碼中使用assert語句可以作為文檔。斷言語句使其他人更容易理解和使用您的代碼,因?yàn)樗鼈冿@式地描述了您的代碼所做的假設(shè)。
- 測試:為了確保滿足某些需求,在單元測試中經(jīng)常使用assert語句。通過在測試中合并assert語句,可以確保代碼正常工作,并且所做的任何更改都不會損壞當(dāng)前功能。
- 安全性:您可以使用assert檢查程序輸入是否符合要求并驗(yàn)證它們。通過這樣做,可以避免諸如緩沖區(qū)溢出和SQL注入攻擊的安全缺陷。
到了這里,關(guān)于Python | assert關(guān)鍵字的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!