简体   繁体   English

有没有办法迭代for循环直到满足条件? (Python)

[英]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.它用于查找每个素数的总和,直到 200 万。 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"? (所以如果 until=10,那么它将打印 19 (2+3+5+7)。但是,我使用的逻辑非常无效,因为素数或非素数序列会查看每个数字,直到被要求的数字。是有办法做到这一点,以便每当 Prime=False 有办法停止“for t in range”?

You can use the break statement:您可以使用 break 语句:

if (condition):
    break;

The break statement will force the control to exit the loop. break 语句将强制控件退出循环。

You can remove the elif statement and there is no need to put i%2==0 because you are only checking odd numbers.您可以删除 elif 语句,无需输入 i%2==0,因为您只检查奇数。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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