Search code examples
pythonoperator-precedence

Regarding left-sided Binding in Python


I'm new to Python and I'm still learning. I've learned the concept of left-sided binding when using operators (and it was taught that only exponentiation uses RIGHT-SIDED BINDING). It was also taught to me that, both * and / have equal priority and Binding of the operator determines the order of computation performed by some operators with equal priority, put side by side in one expression.

But now when teaching compound assignment operators, they used the following example

a = 6
b = 3
a /= 2 * b
print(a)

The answer given is 1.0.

The explanation they have given is as follows.

2 * b = 6

a = 6 → 6 / 6 = 1.0

My question is, isn't a/=2*b is the same thing as a=a/2*b. So when considering a=a/2*b shouldn't the division be considered first becuase of the left sided binding and then the multiplication later.

a = 6 → 6/2 = 3.0

3.0 * b = 9.0.

So shouldn't 9.0 be the answer. Please explain this to me.


Solution

  • The statement a /= 2 * b is equivalent to a /= (2 * b), not (a /= 2) * b, which doesn't make sense in Python.

    If you did interpret it as (a /= 2) * b, then it would expand to (a = a / 2) * b, not a = (a / 2) * b. This is not allowed in Python because a = a / 2 is not an expression and it does not produce a value which could be multiplied by b.

    The answer is that the assignment operator _ = _, and the augmented assignment operators like _ /= _, have a lower precedence than other operators (like _ * _ and _ / _), and they are "right-associative" syntactically so that a = b = c assigns the result c to both a and b; however, it would not be correct to write that this is equivalent to a = (b = c), since this does not make sense in Python for the above reason. Still, _ ** _ is not the only right-associative operator in Python: another one is the ternary operator _ if _ else _, where an expression a if b else c if d else e is equivalent to a if b else (c if d else e), not (a if b else c) if d else e.