我目前正在學習Python3,但我不理解邏輯運算符。這裏是鏈接: http://pymbook.readthedocs.org/en/py3/operatorsexpressions.html#logical-operators 首先,它似乎應該返回「真」或「假」,而不是輸入數字之一。其次,我不明白爲什麼輸出(其中一個輸入數字)是如此。請幫忙,謝謝。Python邏輯運算符
-2
A
回答
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,這個返回確定整個語句值的值的想法更有意義(對我來說,無論如何)
相關問題
- 1. 邏輯&&運算符
- 2. 邏輯運算符
- 3. 邏輯運算符||
- 4. 邏輯運算符
- 5. Python的布爾和邏輯運算符
- 6. 的Python 2.7布爾運算符邏輯
- 7. 結合邏輯運算符
- 8. 邏輯運算符Objective-C
- 9. 邏輯運算符或者
- 10. C++邏輯運算符Q
- 11. C:邏輯運算符
- 12. 邏輯比較運算符
- 13. Java邏輯運算符
- 14. Javascript邏輯運算符:?
- 15. PHP邏輯運算符
- 16. 邏輯與運算符與
- 17. 邏輯運算符在PHP
- 18. Spring SpEL邏輯運算符
- 19. 邏輯AND運算符
- 20. Codeigniter邏輯運算符
- 21. PHP邏輯運算符
- 22. 按位運算符&邏輯
- 23. 使用邏輯運算符
- 24. C++邏輯與運算符
- 25. 邏輯運算
- 26. 如何有多個「和」邏輯運算符和「或」邏輯運算符
- 27. 算術運算符的邏輯?
- 28. 2列的邏輯運算(邏輯或)
- 29. Javascript:使用邏輯運算符與比較運算符
- 30. 邏輯運算符或位運算符(Java)的