Python - 所有循环中的“break” [英] Python - `break` out of all loops
问题描述
我为循环使用了多个嵌套。在上一个循环中,如果
语句存在。当评估为
True
时,循环的所有应该停止,但是这种情况不会发生。它只有
break
s在循环的最内层之外,并且比它继续。如果遇到
break
语句,我需要所有循环来停止。
我的代码:
对于范围(1,1001)中的i:
对于范围(i,1001)中的i2:
i3在范围内(i2,1001):
如果i * i + i2 * i2 == i3 * i3和i + i2 + i3 == 1000:
print i * i2 * i3
break
返回:
$ $ p $ def myfunc():
(i,1001):
i2在范围(i,1001)中:
在范围(i2,1001)中为i3:
如果i * i + i2 * i2 == i3 * i3和i + i2 + i3 == 1000:
print i * i2 * i3
return#退出函数(并停止所有循环)
myfunc()#调用函数
使用 返回
立即退出封闭功能。在这个过程中,所有的循环将被停止。
I am using multiple nested for
loops. In the last loop there is an if
statement. When evaluated to True
all the for
loops should stop, but that does not happen. It only break
s out of the innermost for
loop, and than it keeps on going. I need all loops to come to a stop if the break
statement is encountered.
My code:
for i in range(1, 1001):
for i2 in range(i, 1001):
for i3 in range(i2, 1001):
if i*i + i2*i2 == i3*i3 and i + i2 + i3 == 1000:
print i*i2*i3
break
You should put your loops inside a function and then return:
def myfunc():
for i in range(1, 1001):
for i2 in range(i, 1001):
for i3 in range(i2, 1001):
if i*i + i2*i2 == i3*i3 and i + i2 + i3 == 1000:
print i*i2*i3
return # Exit the function (and stop all of the loops)
myfunc() # Call the function
Using return
immediately exits the enclosing function. In the process, all of the loops will be stopped.
这篇关于Python - 所有循环中的“break”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!