3

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

My code is:

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

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

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75

4 Answers4

6

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.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89
1

The problem is that '&' has higher priority than ==. If you put your last statement like:

(f==1) & (x==2)

You will get your desired result.

magu_
  • 4,766
  • 3
  • 45
  • 79
1

In the second case, your code is:

f == (1 & x) == 2

1 & 2 is 0:

00000001
00000010 &
--------
00000000

So your final statement looks:

1 == 0 == 2

Which is False.

Maroun
  • 94,125
  • 30
  • 188
  • 241
0

Logical AND (and) gives you an answer in true or false (boolean answer) whereas Bitwise AND (&) operator gives you an answer in digits after converting them to binary and applying a truth table on numbers.

Julia Meshcheryakova
  • 3,162
  • 3
  • 22
  • 42
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 29 '22 at 20:25