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

2019-03-01 05:36发布

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条回答
做自己的国王
2楼-- · 2019-03-01 06:09

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.

查看更多
登录 后发表回答