Python:算术表达式的求值顺序

2024-04-26 12:06:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚读了https://courses.cs.washington.edu/courses/cse140/13wi/eval_rules.pdf 在第5页的开头,这个表达式

6 + 7 + 8

评估为:

13 + 8

然后到

21

如果在python中是这样的话,那么为什么呢

2**1**2

计算为2而不是4


Tags: httpspdf表达式evalcsruleseducourses
2条回答

基于python3.xdocs页面(power操作符)

因此,在幂运算符和一元运算符的非偶数化序列中,运算符的求值顺序是从右到左(这并不限制操作数的求值顺序):“-1**2”结果是-1”

因此,表达式被求值为2^1(1^2=1),它本身就是2(或者换句话说,用括号,(2^1^2))

希望有帮助

正如the documentation提到的:

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

以及:

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.

相关问题 更多 >