Search code examples
pythonpython-3.xif-statementbitwise-operators

Bitwise Operator with If Statement and comparison Operators. How does this if statement work?


a = 2
b = 1
if a == 2 | b == 1:
    print(a, b)

this won't print the values of a & b

a = 2
b = 1
if ((a == 2) | (b == 1)):
    print(a, b)

this will print the values

why so?


Solution

  • Operator == in Python has a lower precedence than the operator |. So:

    a == 2 | b == 1
    

    is equivalent to:

    a == (2 | b) == 1
    

    which, in turn, is equivalent to:

    (a == (2 | b)) and ((2 | b) == 1)
    

    Given that a==2, at least one of the subexpressions must be false, regardless of b.