lower = int(input("from:"))
upper = int(input("to:"))
for num in range(lower,upper + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
为什么这段代码将“2”打印为素数? (它是但它不应该打印它)
2%2==0 所以它应该跳过它...
最佳答案
当 num
为 2 时,range(2, num)
为空,所以 if (num % i) == 0:
不执行检查,执行 else
block 。
关于Python 质数 for-else 范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53400108/