例如:
import random
x = random.randint(1, 6)
y = 2
new = x / y
...
现在,假设 x 结果是 5。 在我的程序中执行其他操作之前,如何捕获它是 int 还是 float?
最佳答案
默认情况下,如果你不这样做,整数除法在 python 2 中会有点出乎意料
from __future__ import division
示例:
>>> 5 / 3
1
>>> isinstance(5 / 3, int)
True
说明:Why doesn’t this division work in python?
最后,您始终可以将数字转换为 int:
>>> from __future__ import division
>>> int(5/3)
1
关于Python 确保 x 是 int,而不是讨厌的 float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2939279/