素数发生器 - 蟒蛇

时间:2013-12-20 05:05:54

标签: python primes

似乎程序只是在迭代相同的数字。

x = input("Enter a number: ")
for p in range(2,int(x)+1):
    for i in range(2,p):
        if p%i == 0:
            pass
        else:
            print (p)

print ("Done")

1 个答案:

答案 0 :(得分:4)

x = input("Enter a number: ")
for p in range(2,int(x)+1):
    for i in range(2,p):
        if p%i == 0:
            break    # <== break here (when a factor is found)
    else:            # <==else belongs to the for, not the if
        print (p)

print ("Done")

还解释了here

  

break语句就像在C中一样,突破了最小的封闭   for或while循环。

     

循环语句可能有一个else子句;它在循环时执行   通过列表的耗尽(with for)或者当   condition变为false(with while),但不是循环时   以休息声明终止。这通过以下举例说明   循环,搜索素数: