我对使用 Python 中的逻辑运算符得到的结果有点困惑。我是初学者,使用几本书进行学习,但它们并没有像我想要的那样详细解释。
这是我自己的代码:
five = 5
two = 2
print five and two
>> 2
好像只是输出了两个变量。
five = 5
two = 2
zero = 0
print five and two and zero
所以,我添加了另一个变量整数。然后我打印并得到以下输出:
>> 0
Python 在后台发生了什么?为什么输出不是 7 或 5、2。
最佳答案
Python bool 运算符返回最后评估的值,而不是 True/False。 docs对此有一个很好的解释:
The expression
x and y
first evaluatesx
; ifx
isfalse
, its value is returned; otherwise,y
is evaluated and the resulting value is returned.
关于Python 的逻辑运算符 AND,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18195322/