[英]In python, is 'foo == (8 or 9)' or 'foo == 8 or foo == 9' more correct?
When programming in python, when you are checking if a statement is true, would it be more correct to use foo == (8 or 9)
or foo == 8 or foo == 9
? 在python中编程时,当你检查一个语句是否为真时,使用foo == (8 or 9)
或foo == 8 or foo == 9
会更正确吗? Is it just a matter of what the programmer chooses to do? 这只是程序员选择做的事情吗? I am wondering about python 2.7, in case it is different in python 3. 我想知道python 2.7,以防它在python 3中有所不同。
You probably want foo == 8 or foo == 9
, since: 你可能想要foo == 8 or foo == 9
,因为:
In [411]: foo = 9
In [412]: foo == (8 or 9)
Out[412]: False
In [413]: foo == 8 or foo == 9
Out[413]: True
After all, (8 or 9)
is equal to 8
: 毕竟, (8 or 9)
等于8
:
In [414]: (8 or 9)
Out[414]: 8
Alternatively, you could also write 或者,你也可以写
foo in (8, 9)
This holds for Python3 as well as Python2. 这适用于Python3和Python2。
foo == (8 or 9)
is not the same as foo == 8 or foo == 9
and the latter is the correct form. foo == (8 or 9)
与foo == 8 or foo == 9
,后者是正确的形式。
(8 or 9)
evaluates to 8
since in Python or
evaluates to the first operand (left to right) that is 'truthy', or False
if neither is, so the check becomes a plain foo == 8
. (8 or 9)
计算结果为8
因为在Python中or
计算到第一个操作数(从左到右)是'truthy',否则为False
如果两者都不是),因此检查变为普通foo == 8
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.