Order#
Here I’ll show features related to the order of execution of expressions with different combinations of operators.
Somewhere on the internet I found such a picture describing the order of execution for Python operators.
The top operators are executed first, regardless of where they appear in the expression. Operators at the same level will be executed in the sequence as they are specified in the expression according to the rule specified in the “Associativity” column.
Operator sequence#
The following example show that **
will be executed before *
anyway. Calculation always follows the way \(4^2=16 \rightarrow 16*2 = 32\) and never \(2*4=8 \rightarrow 8^2=64\).
print(2*4**2)
32
Associativity#
As mentioned for the operators /
and *
, they are executed from left to right. So the following example will use logic \(3/3=1 \rightarrow 1*2=2\), not \(3*2=6 \rightarrow 3/6=0.5\).
3/3*2
2.0
One more example shows how associativity rool changes the result with exactly same operands.
In first case it uses logic \(3/3=1 \rightarrow [1/3]=1\);
In second case it uses logic \([3/3]=0 \rightarrow 0/3=0\).
print(3/3%3)
print(3%3/3)
1.0
0.0