如何跳出多个循环? [英] How to break out of multiple loops?

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

问题描述

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

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?

推荐答案

这是另一种简短的方法.缺点是只能打断外循环,但有时正是你想要的.

Here's another approach that is short. The disadvantage is that you can only break the outer loop, but sometimes it's exactly what you want.

for a in xrange(10):
    for b in xrange(20):
        if something(a, b):
            # Break the inner loop...
            break
    else:
        # Continue if the inner loop wasn't broken.
        continue
    # Inner loop was broken, break the outer.
    break

这使用了 for/else 结构,解释如下:为什么python在for和while循环后使用'else'?

This uses the for / else construct explained at: Why does python use 'else' after for and while loops?

关键见解:它只是看起来好像外循环总是会中断.但如果内循环不中断,外循环也不会中断.

Key insight: It only seems as if the outer loop always breaks. But if the inner loop doesn't break, the outer loop won't either.

continue 语句是这里的魔法.它在 for-else 子句中.根据定义,如果没有内部中断,就会发生这种情况.在这种情况下,continue 巧妙地绕过了外部中断.

The continue statement is the magic here. It's in the for-else clause. By definition that happens if there's no inner break. In that situation continue neatly circumvents the outer break.

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

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