print(1!=1 & 1!=1)
print(1!=1 & 2!=2)
Why do the two return different values?
Asked
Active
Viewed 50 times
0
-
7`&` and `|` are bitwise operators in python. – Arkistarvh Kltzuonstev Apr 01 '19 at 13:13
-
use `and`, as `&` means something else. check https://stackoverflow.com/questions/22646463/difference-between-and-boolean-vs-bitwise-in-python-why-difference-i – Zulfiqaar Apr 01 '19 at 13:14
1 Answers
6
&
has a higher precedence than !=
, so your statements are equivalent to
print(1!=(1 & 1)!=1)
print(1!=(1 & 2)!=2)
1&1 is 1, and 1&2 is 0,* so these are equivalent to
print(1!=1!=1)
print(1!=0!=2)
Because !=
supports chaining, these are equivalent to
print((1!=1) and (1!=1))
print((1!=0) and (0!=2))
Which is equivalent to
print(False and False)
print(True and True)
Which is equivalent to
print(False)
print(True)
(*If you're thinking "that's strange, I thought 1 and 2 were both True when evaluated in a boolean context. Shouldn't and-ing them together evaluate to True?", that only works if you use the boolean AND operator and
rather than the bitwise AND operator &
.)

Kevin
- 74,910
- 12
- 133
- 166