Prime numbers list generator immediately closing when run

亡梦爱人 提交于 2019-11-30 21:50:58

问题


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()

but it closes immediately when I try to open the .py file. I think there is a problem with the code.


回答1:


Your code executes and finishes, but it does not compute a list of prime numbers because it contains an error:

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

also, the line num=int is not needed

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()



回答2:


The logic in your if-else is incorrect.

If you get a "clean modulo" in your if block, what do you want to happen? Hint: not pass.

Second, when do you want to append to your prime list?

Not being too specific here as we shouldn't be doing this H/W assignment for you. :)



来源:https://stackoverflow.com/questions/53787372/prime-numbers-list-generator-immediately-closing-when-run

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!