简体   繁体   中英

Is there a way to iterate a for loop until a condition is met? (python)

This is my code:

until=2000000
Prime=True
total=2
for i in range(3,until,2):
    for t in range(3,i,2):
        if i%t == 0 or i%2==0:
            Prime=False
    if Prime==True:
        total+=i
    elif Prime==False:
        Prime=True
print(total)

It is used to find the total of every prime number until two million. This number can be adjusted, and will find the total of every prime until then. (so if until=10, then it would print 19 (2+3+5+7). However, the logic I have used is very ineffective, as the prime or not sequence looks at every number until the asked for number. Is there a way to make it so that whenever Prime=False there is a way to stop the "for t in range"?

You can use the break statement:

if (condition):
    break;

The break statement will force the control to exit the loop.

You can remove the elif statement and there is no need to put i%2==0 because you are only checking odd numbers.

until=10
Prime=True
total=2
for i in range(3,until,2):
    for t in range(3,i,2):
        if i%t == 0:
            Prime=False
    if Prime==True:
        total+=i
print(total)

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