python - Python 2 和 Python 3 中的整数除法

标签 python python-3.x python-2.7 division

如何在 Python 2.7 中将两个数字相除并得到小数的结果?

我不明白为什么会有区别:

在 Python 3 中:

>>> 20/15
1.3333333333333333

在 Python 2 中:

>>> 20/15
1

这不是模数吗?

最佳答案

在 Python 2.7 中,如果输入是整数,则 / 运算符是整数除法。

如果你想要浮点除法(这是我一直喜欢的),只需使用这个特殊的导入:

from __future__ import division

看这里:

>>> 7 / 2
3
>>> from __future__ import division
>>> 7 / 2
3.5
>>>

整数除法使用//,取模使用%:

>>> 7 % 2
1
>>> 7 // 2
3
>>>

正如 user2357112 所评论的,此导入必须在任何其他正常导入之前完成。

关于python - Python 2 和 Python 3 中的整数除法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21316968/

相关文章:

python - 从文本文档中删除一行

python - 在 QListFiew 中过滤/搜索 QFileSystemModel(可能是 QSortFilterProxyModel)

python-2.7 - nlargest 和 nsmallest ;堆 python

跨多个模块的 Python 日志记录

python - ipython 笔记本终端不可用

python - 如何根据另一个DataFrame中的值更新DataFrame中的值?

python-3.x - 为什么 Python 列表推导最后会打印一个 "None"的列表?

python - 洗牌列表,但保持一些元素卡住

python - 在我的图中绘制 Cartopy 中的文本

python - 如何使用 matplotlib 在 python 中保存绘图?