Skip to main content
 首页 » 编程设计

python之**的操作顺序

2025年05月04日14luoye11

我想知道为什么会出现以下情况。 下面的代码首先评估右侧 1**3 然后 2**1

2**1**3 has the value of 2 

但是,对于下面的代码,左侧 7//3 首先被计算,然后是 2*3。最后 1+6-1=6。

1+7//3*3-1 has the value of 6 

请您参考如下方法:

看看 documentation of operator precedence .虽然乘法*和floor除法//的优先级相同,但还是要注意这部分:

Operators in the same box group left to right (except for exponentiation, which groups from right to left).

关于 213 被计算为右关联的约定,请参阅数学堆栈交换网站上的跨站点欺骗:What is the order when doing xyz and why?

TL;DR 是这样的:因为左关联版本 (xy)z 将恰好等于 xy*z,对同一事物使用另一个(更差的)符号是没有用的,因此求幂应该是右结合的。