python - 为什么这不返回正确的除数?
问题描述
我对 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]
解决方案
问题可能是您在迭代列表 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)
了解发生了什么。
推荐阅读
- python - Python 类变量与所有实例共享
- python-3.x - SyntaxError:在 pd.read_csv(io.StringIO(uploaded['Rawdata_2001to2018.csv'] 时解析时出现意外 EOF
- selenium-webdriver - 无法使用 selenium(java) 拖放 web 元素
- python - AttributeError:“TracebackException”对象没有属性“exc_trackback”错误
- xslt - 'tokenize()' 是一个未知的 XSLT 函数
- c++ - libgcc_s_sjlj-1.dll 找不到?
- java - JPA 通过外键查找
- python - 错误输出(Symfony\Component\Process\Exception\ProcessFailedException)
- python - 如何在两个绘图点之间显示“括号”图形并显示两点之间的百分比差异?
- python-3.x - ThreadPoolExecutor 正在将输入数据混合到每个线程上的函数中?视窗