按位'&'链比较中的运算符 [英] Bitwise '&' operator in chained comparison
本文介绍了按位'&'链比较中的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var = 86
print((var < 90) & (var >= 80))
打印 True
。
但是为什么要这样做所有这些打印 False
?
But why do all these print False
?
print(var < 90 & var >= 80)
print(var < 90 & (var >= 80))
print((var < 90) & var >= 80)
print(var < 90 & True)
推荐答案
您应该使用和
运算符代替布尔运算。
You should be using the and
operator instead for boolean operations.
由于python支持链接关系运算符(即,您可以使用 0< var< 100
代替 0< var和var< 100
),并在关系运算符之前将二元运算(即加,减,按位运算等)处理为
Since python supports chaining relational operators (i.e. you can use 0 < var < 100
instead of 0 < var and var < 100
) and processes binary operations (i.e. addition, subtraction, bitwise operations, etc.) before relational operators due to operator precedence, all of the failing cases you posted actually mean something else.
-
var<优先级,您发布的所有失败案例实际上都具有其他含义。 90& var> = 80
等效于(var< 90& var)和(90& var> = 80)
-
var< 90& (var> = 80)
等效于var< 90&真
,要看第四种情况。 -
(var< 90)& var> = 80
也类似于第4种情况(此解析为True& var> = 80
然后将解析为0> = 80
)。 -
var< 90& True
等效于var< (90&True)
。&
运算符的实现被设计为,如果其中一个操作数不是整数,则返回0
是动态类型化的另一个最大陷阱),这就是为什么所有这些类似的语句都解析为var< 0
这是错误的。
var < 90 & var >= 80
is equivalent to(var < 90 & var) and (90 & var >= 80)
var < 90 & (var>=80)
is equivalent tovar < 90 & True
for which look at the 4th case.(var<90) & var>=80
is also similar to the 4th case (this resolves toTrue & var >= 80
which will then resolve to0 >= 80
).var < 90 & True
is equivalent tovar < (90 & True)
. The implementation of the&
operator is designed to return0
if either one of the operands is not an integer (which is another one of the biggest pitfalls of dynamic typing), which is why all such similar statements resolve tovar < 0
which is false.
这篇关于按位'&'链比较中的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文