奇怪的蟒蛇行为
我无聊地摆弄 ipython 控制台,并遇到了以下行为,我不太理解
In [1]: 2**2
Out[1]: 4
In [2]: 2**2**2
Out[2]: 16
In [3]: 2**2**2**2
Out[3]: 65536
In [4]: 2**2**2**2**2
[4] 的答案是不是 4294967296L,这是一个很长的数字,但我不能真正弄清楚为什么。
该号码可以在这里找到:http://pastie.org/475714
(Ubuntu 8.10,python 2.5.2 , ipython 0.8.4)
(Mac OS X 10.5.6、Python 2.5.1)
I was bored and playing around with the ipython console and came upon the following behaviour I don't really understand
In [1]: 2**2
Out[1]: 4
In [2]: 2**2**2
Out[2]: 16
In [3]: 2**2**2**2
Out[3]: 65536
In [4]: 2**2**2**2**2
The answer to [4] is not 4294967296L, it's a very long number, but I can't really figure out why.
The number can be found here: http://pastie.org/475714
(Ubuntu 8.10, python 2.5.2, ipython 0.8.4)
(Mac OS X 10.5.6, Python 2.5.1)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
从右到左计算,让我们看看 Python 为获得这些答案所经历的步骤:
Evaluating right-to-left, let's look at the steps Python is going through to get these answers:
Python 从右到左进行数学幂运算。 例如, IN[2] 正在执行:
2**(4) = 16
IN[3] = 2222 = 22**(4) = 2**16 = 65536
如果你想从左到右计算,你需要括号。 OUT[4] 没有输出你想要的答案的原因是因为这个数字是天文数字,Python 无法打印出来。
2^65536 = 极其巨大
Python is going right to left on the mathematical power operation. For example, IN[2] is doing:
2**(4) = 16
IN[3] = 2222 = 22**(4) = 2**16 = 65536
You would need parenthesis if you want it to calculate from left to right. The reason OUT[4] is not outputting the answer you want is because the number is astronomical and Python cannot print it out.
2^65536 = extremely huge
** 运算符的优先级使得计算从右到左(而不是预期的从左到右)。 换句话说:
The precedence of the ** operator makes the evaluation goes from right-to-left (instead of the expected left-to-right). In other words:
这是因为 Python 中的优先顺序导致该方程从右到左计算。
This is because the order of precedence in Python causes this equation to be evaluated from right-to-left.
正如其他答案已经说过的那样,这是因为
**
是从右到左评估的。这是文档链接,其中描述了所有优先级。
As the other answers already said, it's because
**
is evaluated from right to left.Here is the documentation link, where all the precedences are described.