I want to know why does the following happen.
The code below evaluates right side 1**3
first then 2**1
2**1**3 has the value of 2
However, for the below code left side 7//3
is evaluated first then 2*3
. Finally 1+6-1=6
.
1+7//3*3-1 has the value of 6
Take a look at the documentation of operator precedence. Although multiplication *
and floor division //
have the same precedence, take note of this part:
Operators in the same box group left to right (except for exponentiation, which groups from right to left).
For the convention of 213 being evaluated right-associative, see cross-site dupe on the math stackexchange site What is the order when doing xyz and why?
To put it simply, since the left-associative version (xy)z would just equal xy*z, it's not useful to have another (worse) notation for the same thing, so exponentiation should be right associative.
Almost all operators in Python (that share the same precedence) have left-to-right associativity. For example:
1 / 2 / 3 ≡ (1 / 2) / 3
One exception is the exponent operator which is right-to-left associativity:
2 ** 3 ** 4 ≡ 2 ** (3 ** 4)
That's just the way the language is defined, matching mathematical notation where abc ≡ a(bc)
.
If it were (ab)c
, that would just be abc
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With