首页 > 解决方案 > 为什么这不返回正确的除数?

问题描述

我对 Python 和一般编码非常陌生。我学了一点 Python 2,因为它是最好的免费版本 :) 下面是我写的代码:

num = int(input("What number would you like to check the divisors of? "))
Divisors = list(range(1, num+1))
for element in Divisors:
    if num % element != 0:
        Divisors.remove(element)
print(Divisors)

这是它打印出来的:

What number would you like to check the divisors of? 12
[1, 2, 3, 4, 6, 8, 10, 12]

标签: pythonlistmodulomod

解决方案


问题可能是您在迭代列表 Divisors 时对其进行了修改。它使您的代码跳过数组中的一些元素,尝试像这样打印当前元素:

num = int(input("What number would you like to check the divisors of? "))
Divisors = list(range(1, num+1))
for element in Divisors:
    print("The current element is", element)
    if num % element != 0:
        Divisors.remove(element)

了解发生了什么。


推荐阅读