0
>>> 5 > 4 & 6 > 5

Why does the above expression give False in Python, if 5 > 4 is True and 6 > 5 is also True?

martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

6

Because & (bitwise "and") has a higher precedence than >, so 5 > 4 & 6 > 5 is actually evaluated as 5 > 4 > 5 which is obviously False.

Operator precedence on Python docs.

Paolo
  • 20,112
  • 21
  • 72
  • 113
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
1

In python the & operator represents the bitwise AND operator, which basically takes the binary form of an integer, and masks the binary form of the first number by the second number.

For example, 10 & 3 returns 2 because the binary form of 10 is 1010, and with the mask of 3, we take the last three digits, and find the value of the resulting binary. In this case, it's 010, which in decimal is 2.

The operator you're looking for is the literal and operator!:

>>> 5 > 4 and 6 > 5 
True

Or better (I believe you already know this):

>>> 6 > 5 > 4
True
Red
  • 26,798
  • 7
  • 36
  • 58
  • 1
    Given that the question is tagged with "bitwise-operators", I'll take it that OP knows what `&` is in Python. The issue appears to be about the precedence, not the expectation from `&` – DeepSpace Mar 11 '21 at 19:17