我对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]
问题可能是在迭代列表时修改了除数。它使您的代码跳过数组中的一些元素,尝试像这样打印当前元素:
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)
了解发生了什么。
在迭代中修改除数会产生副作用。相反,你可以使用列表比较来得到你想要的。
num = int(input("What number would you like to check the divisors of? "))
Divisors = list(range(1, num+1))
Divisors = [ element for element in Divisors if num % element == 0 ]
输出:
[1, 2, 3, 4, 6, 12]