0

Say I define a and b as follows:

a = 1
b = 1

Then I test:

a == 1
#True

5>4
#True

a==1 & b==1
#True

5>4 & 4>3
#True

a==1 & 5>4
#False

What is going on with the last one? I would like to be able to test the last inequality and get the result of True.

bill999
  • 2,147
  • 8
  • 51
  • 103

2 Answers2

6

In Python & is for bit operations with numbers, not logic. Use and and or instead.

Dmitry Torba
  • 3,004
  • 1
  • 14
  • 24
  • 1
    In the last example, the `&` operator takes precedence on the `==` operator. So it is evaluated first, like this: `a == (1 & 5) > 4`. Then `a == 1 > 5` which is converted to `int(True) > 5`, which is `False`. – Laurent LAPORTE Aug 22 '16 at 21:26
-1

Unlike C, all comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Also unlike C, expressions like a < b < c have the interpretation that is conventional in mathematics:

Which means:

a==1 & 5>4 is equal to 
a == ( 1 % 5 ) > 4
a == 1 > 4
True > 4

False