Python Operator Precedence with Shortcut Operator?

92 views Asked by At

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?

2

There are 2 answers

0
Tom Karzes On BEST ANSWER

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.

1
Manuel A. Martinez On

Here's a link (Prepbytes - Operator Precedence) that describes that Assignment operators (=, +=, -=, *=, /=, //=, %=, **=, &=, |=, ^=, <>=) have the lowest precedence. My understanding is that the assignment operators are calculated at the moment of assigning the value to the variable. Python first works on the operations to the right of the assignment operator 2 * 3 then lastly works on the shortcut (assignment) operator calculation x /= 6.

if x=6, then x /= 2 * 3 is calculated as:

x = x / (2 * 3)

x = 6 / (2 * 3)

x = 6 / 6

x = 1.0