开发者

What is the purpose of the `//` operator in python? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

What is the reason for having '//' in Python?

What is the purpose of the // operator?

x=10
y=2
print x/y
print x//y

Both 开发者_Python百科output 5 as the value.


Integer division vs. float division:

>>> 5.0/3
3: 1.6666666666666667
>>> 5.0//3
4: 1.0

Or as they put it in the Python docs, // is "(floored) quotient of x and y". The above example was run in Python 2.7.2, which only behaves that way for floating point numbers. If you were to use integers in 2.7.2 you'd get:

>>> 5/3
9: 1
>>> 5//3
10: 1

In Python 3.x you get different results, so if you really want the floored version, get into the habit of using // as some day it'll matter:

Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 5/3
1.6666666666666667
>>> 5//3
1
>>> 5.0/3
1.6666666666666667
>>> 5.0//3
1.0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜