I have a line of code in my script that has both these operators chained together. From the documentation reference BOOLEAN AND has a lower precedence than COMPARISON GREATER THAN. I am getting unexpected results here in this code:
>>> def test(msg, value):
... print(msg)
... return value
>>> test("First", 10) and test("Second", 15) > test("Third", 5)
First
Second
Third
True
I was expecting Second or Third test to happen before the fist one, since >
operator has a higher precedence. What am I doing wrong here?
https://docs.python.org/3/reference/expressions.html#operator-precedence
Because you are looking at the wrong thing. call
(or function call) takes higher precendence over both and
as well as >
(greater than) . So first function calls occur from left to right.
Python will get the results for all function calls before either comparison happens. The only thing that takes precendence over here would be short circuiting , so if test("First",10)
returned False, it would short circuit and return False.
The comparisons and and
still occur in the same precendence , that is first the result of test("Second", 15)
is compared against test("Third", 5)
(please note only the return values (the function call already occured before)) . Then the result of test("Second", 15) > test("Third", 5)
is used in the and
operation.
From the documentation on operator precedence -