2015-01-02 229 views

回答

7

操作如果沒有元素是False(或同等的值,如0)返回最後元件。

例如,

>>> 1 and 4 
4 # Given that 4 is the last element 
>>> False and 4 
False # Given that there is a False element 
>>> 1 and 2 and 3 
3 # 3 is the last element and there are no False elements 
>>> 0 and 4 
False # Given that 0 is interpreted as a False element 

操作返回第一元件不是False。如果沒有這樣的值,則返回False

例如,

>>> 1 or 2 
1 # Given that 1 is the first element that is not False 
>>> 0 or 2 
2 # Given that 2 is the first element not False/0 
>>> 0 or False or None or 10 
10 # 0 and None are also treated as False 
>>> 0 or False 
False # When all elements are False or equivalent 
1

這會引起混亂 - 你不是第一個被它絆倒。

Python將0(零),False,None或空值(如[]或'')視爲false,其他都視爲true。

的 「與」 和 「或」 運算符返回根據這些規則操作數之一:

  • 「x和y」 是指:如果x爲假,則x,否則ÿ
  • 「×或Y」是指:如果x是 假,則Y,否則x

您引用不一樣清楚,因爲它可以解釋這個頁面,但他們的榜樣是正確的。

1

我不知道這是否有幫助,但是擴展@ JCOC611的答案,我認爲它是返回確定邏輯語句值的第一個元素。因此,對於一串'和',第一個False值或最後一個True值(如果所有值均爲True)確定最終結果。同樣,對於一串'或',第一個True值或最後一個False值(如果所有值都是False)確定最終結果。

>>> 1 or 4 and 2 
1 #First element of main or that is True 
>>> (1 or 4) and 2 
2 #Last element of main and that is True 
>>> 1 or 0 and 2 
1 
>>> (0 or 0) and 2 
0 
>>> (0 or 7) and False 
False #Since (0 or 7) is True, the final False determines the value of this statement 
>>> (False or 7) and 0 
0 #Since (False or 7) is True, the final 0(i.e. False) determines the value of this statement) 

第一行讀爲1或(4和2),因爲1使最終語句爲真,所以它的值被返回。第二行由'and'語句管理,所以最後的2是返回的值。在接下來的兩行中使用0作爲False也可以顯示這一點。

最終,我通常比較喜歡在布爾語句中使用布爾值。取決於與布爾值相關的非布爾值總是讓我感到不安。另外,如果你用布爾值構造一個布爾型staement,這個返回確定整個語句值的值的想法更有意義(對我來說,無論如何)