Python - 从所有循环中`break` [英] Python - `break` out of all loops

查看:25
本文介绍了Python - 从所有循环中`break`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用多个嵌套的 for 循环.在最后一个循环中有一个 if 语句.当评估为 True 时,所有 for 循环都应该停止,但这不会发生.它只 break 脱离最内层的 for 循环,然后继续运行.如果遇到 break 语句,我需要所有循环停止.

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 breaks 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.

我的代码:

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

使用 return 立即退出封闭函数.在这个过程中,所有的循环都会停止.

Using return immediately exits the enclosing function. In the process, all of the loops will be stopped.

这篇关于Python - 从所有循环中`break`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆