Search code examples
pythonshortcutoperator-precedence

Python Operator Precedence with Shortcut Operator?


I understand that Python follows an operator precedence with the acronym PEMDAS or P-E-MD-AS

Now Python happens to use shortcut operators so for example if I were to write

x=5
x=x+1

This could be re-written as

x+=1

Now I noticed something a bit odd when I took this a step further and tried to have multiple operations so for example

x=6
y=2

x=x/2*3

Going left to right x then becomes 9.0

If I try to re-write the above with shortcut syntax I get the following

x/=2*3

But this results in 1.0

It seems that the multiplication on the right hand side seems to take place before the division shortcut operator? I thought we would be working from left to right so I am confused how this works

Is this always the case? If so why does it work this way?


Solution

  • You can't rewrite x=x/2*3 using the op= operators. The reason is that x op= y is (mostly) equivalent to x = x op y. But in your case, you have x=x/2*3, which groups as x=(x/2)*3. This does not have the form x = x op y. The top-level operator of the right hand side is *, and the left operand is x/2, not x. The best you could do is split it up into two statements: x /= 2 followed by x *= 3, but I don't think that improves anything.