Home > Back-end >  Is there a way to iterate a for loop until a condition is met? (python)
Is there a way to iterate a for loop until a condition is met? (python)

Time:06-21

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

CodePudding user response:

You can use the break statement:

if (condition):
    break;

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

CodePudding user response:

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)
  • Related