如何摆脱多重循环? [英] How to break out of multiple loops?

查看:95
本文介绍了如何摆脱多重循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码(不起作用):

Given the following code (that doesn't work):

while True:
    #snip: print out current state
    while True:
        ok = get_input("Is this ok? (y/n)")
        if ok.lower() == "y": break 2 #this doesn't work :(
        if ok.lower() == "n": break
    #do more processing with menus and stuff

有没有办法使这项工作有效?还是我要进行一次检查以打破输入循环,然后再进行另一项限制较大的检查(如果用户满意的话)进入外部循环以全部打破?

Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?

推荐答案

我的第一个直觉是将嵌套循环重构为一个函数,并使用return进行分解.

My first instinct would be to refactor the nested loop into a function and use return to break out.

这篇关于如何摆脱多重循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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