0

print(1!=1 & 1!=1) print(1!=1 & 2!=2) Why do the two return different values?

glibdud
  • 7,550
  • 4
  • 27
  • 37
rain
  • 1

1 Answers1

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