质数列表生成器在运行时立即关闭 [英] Prime numbers list generator immediately closing when run
本文介绍了质数列表生成器在运行时立即关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试制作一个质数列表.
I'm trying to make a list of prime numbers.
primes = []
num=int
for num in range (2,100):
for x in range (2, num):
if (num % x) == 0:
pass
else:
primes.append(num)
break
print(primes)
input()
但是当我尝试打开 .py 文件时它会立即关闭.我认为代码有问题.
but it closes immediately when I try to open the .py file. I think there is a problem with the code.
推荐答案
您的代码执行并完成,但它没有计算素数列表,因为它包含一个错误:
Your code executes and finishes, but it does not compute a list of prime numbers because it contains an error:
当您测试每个 num
以查看它是否为质数时,您可以测试所有可能的除数(正如您尝试做的那样),如果找到单个除数则退出.如果在测试完所有除数后都没有找到除数,则仅将您的数字添加到列表中
When you test each num
to see if it's prime, you can test all possible divisors (as you try to do) and quit if you find a single divisor. If no divisor has been found when you've tested them all, only then add your number to the list
此外,不需要 num=int
行
primes = []
for num in range (2,100):
is_prime=True
for x in range (2, num):
if (num % x) == 0:
is_prime=False
break
if is_prime:
primes.append(num)
print(primes)
input()
这篇关于质数列表生成器在运行时立即关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文