【Python】Python中的短路邏輯

1、python中哪些對象會被當成 False 呢?而哪些又是 True 呢?

在Python中,None、任何數值類型中的0、空字符串“”、空元組()、空列表[]、空字典{}都被當作False,還有自定義類型,如果實現了  __ nonzero __ () 或 __ len __ () 方法且方法返回 0 或False,則其實例也被當作False,其他對象均爲True。


2、簡單的邏輯運算

	True  and True    ==> True					
	True  and False   ==> False					
	False and True    ==> False					
	False and False   ==> False		
	True  or True    ==> True
	True  or False   ==> True
	False or True    ==> True
	False or False   ==> False

3. 短路邏輯

  • 表達式從左至右運算,若 or 的左側邏輯值爲 True ,則短路 or 後所有的表達式(不管是 and 還是 or),直接輸出 or 左側表達式 。
  • 表達式從左至右運算,若 and 的左側邏輯值爲 False ,則短路其後所有 and 表達式,直到有 or 出現,輸出 and 左側表達式到 or 的左側,參與接下來的邏輯運算。
  • 若 or 的左側爲 False ,或者 and 的左側爲 True, 則不能使用短路邏輯。
def fun():
	print("hello, world")

>>> print(0 and fun()) # fun()函數被短路
0

>>> print(fun() and 0) # 先運行fun()函數,fun()函數無返回值None,故0被短路
hello, world
None

>>> print(1 and fun()) # fun()函數未被短路,運行fun函數,輸出hello,world,再返回邏輯運算結果
hello, world
None

>>> print(0 or fun()) # fun()函數未被短路,運行fun函數,輸出hello,world,再返回邏輯運算結果
hello, world
None

>>> print(fun() or 0) # fun()函數未被短路,運行fun函數,輸出hello,world,再返回邏輯運算結果
hello, world
0

>>> print(1 or fun()) # fun()函數被短路
1

參考:https://www.cnblogs.com/an9wer/p/5475551.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章