Search code examples
pythonoperator-precedence

Does the 'or' operator or the equality operator have higher precedence in Python?


Every precedence table I look at for Python states the equality(==) operator is evaluated before the 'or' keyword. Why then is '1' printed for this code? I thought the expression would evaluate as false, and the if block wouldn't run.

number = 1
if number == 0 or 1:
    print(number)

How about the following code? Why isn't 'False' printed? Instead, the integer 1 is printed. It confuses me how the variable 'a' gets assigned as 1 instead of as a False boolean value.

number = 1
a = (number == 0 or 1)
print(a)

Solution

  • Well, you are correct. == does evaluate before or. In the case of if number == 1 or 1, what happens is that python evaluates numbers that aren't 0 as True. So the first "argument" (number == 1) will evaluate to False, while 1 will evaluate to True. And False or True will always be True.

    The other case (a = (number == 0 or 1)) is a little more tricky. In the case of having an assignment of a variable to multiple expressions chained with or, Python will assign the variable to the first expression that evaluates to True and if it doesn't find any, it will assign to the last expression.

    In this case, the first expression (number == 0) is False while 1 on the other hand is True. a therefore gets assigned the value of the second expression, which is 1.