简体   繁体   中英

Prime number generator - python

It seems the program just keeps iterating over the same numbers.

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

Also explained here

The break statement, like in C, breaks out of the smallest enclosing for or while loop.

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM