Python bool邏輯踩坑

邏輯運算

Python中用and, or, not 表示邏輯與,或,非。 其中and返回最後,或者致使短路的操做數;or返回第一真值或者最後的操做數bash

In [89]: 1 and 2   # 最後的操做數
Out[89]: 2

In [90]: 1 and 0 and 2   # 致使短路的操做數
Out[90]: 0

In [91]: 1 or 0 # 第一真值
Out[91]: 1

In [92]: 0 or 1 or 2 # 第一真值
Out[92]: 1

In [94]: False or 0 or 9 # 第一真值也是最後的操做數
Out[94]: 9
複製代碼

Python中的True和False

在Python中,None、任何數值類型中的0、空字符串「」、空元組()、空列表[]、空字典{}都被看成False,還有自定義類型,若是實現了  __ nonzero __ () 或 __ len __ () 方法且方法返回 0 或False,則其實例也被看成False,其餘對象均爲True。ui

當只有一個運算符時:spa

True  and True    ==> True                  True  or True    ==> True
    True  and False   ==> False                 True  or False   ==> True
    False and True    ==> False                 False or True    ==> True
    False and False   ==> False                 False or False   ==> False
複製代碼

短路邏輯

  • 表達式從左至右運算,若or的左側邏輯值爲True,則短路or後全部的表達式(無論是and 仍是or),直接輸出or左側表達式 。
  • 表達式從左至右運算,若and的左側邏輯值爲False,則短路其後全部and表達式,直到有or 出現,輸出and左側表達式到or的左側,參與接下來的邏輯運算。
  • or的左側爲False,或者and的左側爲True則不能使用短路邏輯。

舉個栗子:code

def a():
    print("a is true")
    return True

def b():
    print("b is true")
    return True

def c():
    print("c is false")
    return False

def d():
    print("d is false")
    return False

print(a() and b() and c() and d())
print("*"*20)

print(a() or b() or c() or d())
print("*"*20)

print(a() and d() and c() and b())
複製代碼

執行結果:對象

a is true
b is true
c is false
False
********************
a is true
True
********************
a is true
d is false
False
複製代碼
相關文章
相關標籤/搜索