当前位置: 动力学知识库 > 问答 > 编程问答 >

Prime number in python, prog not working

问题描述:

After I run this, it doesn't print anything:

for n in range(2,100):

for x in range(2,n):

if n%x == 0:

break

else:

if n==x:

print n,'is a prime number'

网友答案:

if n==x will never be true, because the inner loop only runs for values of x from 2 to n-1.

If you need to check that the inner loop ran to completion, use else after the for itself. This will execute the else if break hasn't been performed:

for n in range(2,100):
    for x in range(2,n):
        if n%x == 0:
             break
    else:
        print n,'is a prime number'

A more Pythonic way to do this is by using all with a generator expression:

for n in range(2,100):
    if all(n%x != 0 for x in range(2,n)):
        print n,'is a prime number'
网友答案:

Simple logic dictates this - anything with a remainder of 0 will break out of the loop, and any value modulo itself will be 0, so your else block will never be reached where the contained if will be run.

分享给朋友:
您可能感兴趣的文章:
随机阅读: