python - 如何在 Python 中检查结果是否为整数?

标签 python for-loop integer

<分区>

我有一个简单的任务来计算数字,例如:

a = 7
b = 9
result = 0

for _ in (0:100):
     result = a / b
     b += 1

当结果是整数时,如何停止 for 循环?

检查方法 is_integer() 是否不符合我的期望。

我必须使用 Python 2.6

最佳答案

使用 %1。模运算返回余数,因此如果您尝试除以 1 而余数为 0,则它必须是整数。

if result % 1 == 0:
    print "result is an integer!"

使用this post中提到的方法或 this post :

if result.is_integer():

如评论中所述,您可以使用:

while result % 1 != 0:

使循环重复直到你得到一个整数。

关于python - 如何在 Python 中检查结果是否为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34692645/

相关文章:

javascript - 当循环内的 if 子句中断时,在函数中返回 false

python - 为什么 python re 模块不能与 @ 一起工作?

python - 对给定组标签中的数据进行分类

一行中的python多个 'for'语句

c++ - 为什么最负的 int 值会导致模棱两可的函数重载错误?

JavaFX ComboBox 更改值导致 IndexOutOfBoundsException

php - 在 MySQL 中使用 "signed"INT?

Python 'astype' 不工作

python - re.sub : non-greedy doesn't work as expected

vba - 自身进行变量迭代-不同类型的不同行为