逻辑与按位运算符AND

逻辑与按位运算符AND

问题描述:

即使我读到其他一些关于它的问题,我也不理解& and 之间的区别.

I don’t understand the difference between & and and, even if I read some other questions about it.

我的代码是:

f=1
x=1

f==1 & x==1
Out[60]: True

f==1 and x==1
Out[61]: True

f=1
x=2

f==1 and x==2
Out[64]: True

f==1 & x==2
Out[65]: False

为什么是第二个& False ,而第一个是 True ?

Why is it the second & False, whereas the first is True?

问题是& 的运算符优先级高于 == .

The issue is that & has higher operator precedence than ==.

>>> (f == 1) & (x == 2)
True
>>> f == (1 & x) == 2
False

也许这似乎是不直观的,但是& 实际上是要在数字之间用于特定类型的计算:

Perhaps this seems unintuitive, but & is really meant to be used between numbers for particular kinds of calculations:

>>> 3 & 5
1

因此它与 + * 之类的运算符具有相似的优先级,明智的做法是应在 == 之前对它们进行评估.完全不打算将其与相似地使用.

so it has similar precedence to operators like + and *, which sensibly should be evaluated before ==. It's not meant to be used in a similar manner to and at all.