Python 逻辑运算符

Python Logical Operators

我目前正在学习Python3,但我不懂逻辑运算符。链接在这里: http://pymbook.readthedocs.org/en/py3/operatorsexpressions.html#logical-operators 首先,它似乎应该 return "True" 或 "False" 而不是输入数字之一。其次,我不明白为什么输出(输入数字之一)如此。请帮忙,谢谢。

运算符 and returns last 元素如果没有元素是 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

运算符 returns 第一个 不是 False 的元素。如果没有这个值,则 returns 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

这可能会令人困惑 - 您不是第一个被它绊倒的人。

Python 将 0(零)、False、None 或空值(如 [] 或 '')视为假,将其他任何值视为真。

"and" 和 "or" 运算符 return 根据这些规则的操作数之一:

  • "x and y" 表示:如果 x 为假则 x,否则为 y
  • "x or y" 表示:如果 x 是 false 然后 y,否则 x

您引用的页面没有尽可能清楚地解释这一点,但他们的示例是正确的。

我不知道这是否有帮助,但为了扩展@JCOC611 的答案,我认为它返回确定逻辑语句值的第一个元素。所以,对于一串 'and' 来说,第一个 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 or (4 and 2),所以由于1使最终语句为真,所以返回它的值。第二行由 'and' 语句控制,因此最后的 2 是返回值。在接下来的两行中使用 0 as False 也可以显示这一点。

最终,我通常更愿意在布尔语句中使用布尔值。依赖与布尔值关联的非布尔值总是让我感到不安。另外,如果你想用布尔值构造一个布尔语句,这种返回决定整个语句值的值的想法更有意义(无论如何对我来说)