欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解Python 中的短路評估

 更新時間:2023年06月09日 09:35:48   作者:跡憶客  
短路是指當表達式的真值已經(jīng)確定時終止布爾運算,Python 解釋器以從左到右的方式計算表達式,這篇文章主要介紹了Python 中的短路評估,需要的朋友可以參考下

本文是關(guān)于使用邏輯運算符在 Python 中顯示短路行為。

Python 中的邏輯運算符

or (或)運算符

OR:兩個操作數(shù)均使用 Python or 運算符求值。 如果任一操作數(shù)為 True,則 or 運算符返回 True。

但是,僅當所有給定表達式或操作數(shù)都返回 False 時,or 運算符才會返回 False。

OR運算符邏輯表:

第一值第二值輸出
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

上述 OR 運算符在 Python 控制臺中的表示:

>>> True or True
True
>>> True or False
True
>>> False or True
True
>>> False or False
False

Python 還允許我們使用 OR 運算符比較多個表達式。

>>> (5 < 10) or (8 < 5)
True
>>> (5 < 10) or (8 < 5) or (2 == 2) or (9 != 8)
True

AND 運算符

AND:當使用 Python and 運算符時,兩個操作數(shù)都會被求值,如果任何給定的表達式或運算符不為真,則返回 False。 and 運算符僅在給定表達式或操作數(shù)都為 True 時才返回 True。

AND運算符邏輯表:

第一值第二值輸出
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

上述 AND 運算符在 Python 控制臺中的表示:

>>> True and True
True
>>> True and False
False
>>> False and True
False
>>> False and False
False

使用 AND 運算符比較多個表達式。

>>> (5 < 10) and (8 < 5)
False
>>> (5 < 10) and (8 < 5) and (2 == 2) and (9 != 8)
False
>>> (10 == 10) and (8 != 5) and (2 == 2) and (9 != 8)
True

什么是短路

短路是指當表達式的真值已經(jīng)確定時終止布爾運算。 Python 解釋器以從左到右的方式計算表達式。

Python 的大量布爾運算符和函數(shù)允許短路。

def exp(n):
	print("Hello")
	return n

為了了解短路是如何發(fā)生的,我們將使用上述函數(shù)作為操作數(shù)或表達式之一,當 Python 解釋器執(zhí)行它時,它將打印單詞“Hello”。

在 Python 中使用 AND 運算符進行短路

使用 and 運算符:

>>> True and exp(1)
Hello
1

Python 解釋器在上面的代碼中從左到右評估代碼。 根據(jù) AND 運算符的邏輯表,表達式必須為 True 才能得到 True 布爾值。

Python 解釋器評估我們的函數(shù)只是因為第一個值設(shè)置為 True。

如果我們將初始值設(shè)置為 False 會怎樣? 觀察下面的代碼:

>>> False and exp(1)
False

由于初始值設(shè)置為 False,Python 解釋器會忽略后面的表達式,從而節(jié)省執(zhí)行時間。

交換表達式:

>>> exp(1) and True
Hello
True
>>> exp(1) and False
Hello
False

在這些代碼中,我們的初始表達式是我們之前創(chuàng)建的函數(shù)。 Python 解釋器首先評估給定的函數(shù),導(dǎo)致輸出“Hello”。

在 Python 中使用 OR 運算符進行短路

使用或運算符:

>>> True or exp(1)
True

從左到右評估代碼。 將初始值設(shè)置為 True 可以讓 Python 解釋器忽略后面表達式的執(zhí)行,也就是給定的函數(shù)。

因此,根據(jù) OR 運算符的給定邏輯表,輸出為 True。

>>> False or exp(1)
Hello
1

Python 解釋器執(zhí)行上面代碼中的函數(shù),因為前一個值設(shè)置為 False。

交換表達式:

>>> exp(1) or True
Hello
1
>>> exp(1) or False
Hello
1

當我們交換表達式時,我們創(chuàng)建的函數(shù)每次都會執(zhí)行,因為它是 Python 解釋器評估的第一個操作數(shù)。

考慮以上任一代碼示例,or 運算符將返回 True 布爾值。

但是,如果我們使用 or 運算符得到一個 False 布爾值,我們可以稍微調(diào)整創(chuàng)建的函數(shù)。

def exp():
	print("Hello")
	return False
>>> exp()
Hello
False

經(jīng)過以上改動后,每當我們調(diào)用 exp() 函數(shù)時,它只會在向控制臺打印 Hello 后返回 False 布爾值。

>>> exp() or True
Hello
True
>>> exp() or False
Hello
False

由于該函數(shù)在每次調(diào)用時只返回一個 False 布爾值,Python 解釋器必須評估后一個表達式或操作數(shù)。

到此這篇關(guān)于Python 中的短路評估的文章就介紹到這了,更多相關(guān)Python短路評估內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論