Python的逻辑运算符AND [英] Python's Logical Operator AND
问题描述
我对使用Python中的逻辑运算符获得的结果感到有些困惑.我是一个初学者,正在研究一些书籍,但是它们并没有像我所希望的那样详尽地解释.
I'm a little confused with the results I'm getting with the logical operators in Python. I'm a beginner and studying with the use of a few books, but they don't explain in as much detail as I'd like.
这是我自己的代码:
five = 5
two = 2
print five and two
>> 2
似乎只是输出两个变量.
It seems to be just outputting the two variable.
five = 5
two = 2
zero = 0
print five and two and zero
因此,我添加了另一个变量整数.然后我打印并得到以下输出:
So, I added another variable integer. Then I printed and got the following output:
>> 0
Python在后台发生了什么?为什么输出的不是7或5、2之类的.
What is going on with Python in the background? Why isn't the output something like 7 or 5, 2.
推荐答案
Python布尔运算符返回最后计算的值,而不是True/False. 文档对此有很好的解释:
Python Boolean operators return the last value evaluated, not True/False. The docs have a good explanation of this:
表达式
x and y
首先计算x
;如果x
是false
,则返回其值;否则,将评估y
并返回结果值.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!