How to break out of multiple loops?

后端 未结 30 3900
情书的邮戳
情书的邮戳 2020-11-21 05:48

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)\")
          


        
30条回答
  •  梦如初夏
    2020-11-21 06:26

    Another way of reducing your iteration to a single-level loop would be via the use of generators as also specified in the python reference

    for i, j in ((i, j) for i in A for j in B):
        print(i , j)
        if (some_condition):
            break
    

    You could scale it up to any number of levels for the loop

    The downside is that you can no longer break only a single level. It's all or nothing.

    Another downside is that it doesn't work with a while loop. I originally wanted to post this answer on Python - `break` out of all loops but unfortunately that's closed as a duplicate of this one

提交回复
热议问题