print(a ** b ** c) - wrong precedence order - Pyth

2019-03-01 05:38发布

问题:

I tried to print(2 ** 3 ** 2) to test precedence order, but in Python then Python returned me 512.0 as result. I expected Python would take 2 first, then to the power 3 = 8. Then 8, to the power 2 returning 64 as result (since operations are read from left to the right).

But instead, Python read 2 ** 3 ** 2 = 2 ** 9 = 512 (from right to the left).

Could someone explain why did this happen?

回答1:

It is described to behave that way in the docs

The power operator binds more tightly than unary operators on its left; it binds less tightly than unary operators on its right. The syntax is:

power ::=  ( await_expr | primary ) ["**" u_expr]

Thus, in an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left (this does not constrain the evaluation order for the operands): -1**2 results in -1.

To be pedantic your question is not about precedence in this case, but rather associativity.