How to break out of multiple loops?

后端 未结 30 3243
情书的邮戳
情书的邮戳 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:21

    There is no way to do this from a language level. Some languages have a goto others have a break that takes an argument, python does not.

    The best options are:

    1. Set a flag which is checked by the outer loop, or set the outer loops condition.

    2. Put the loop in a function and use return to break out of all the loops at once.

    3. Reformulate your logic.

    Credit goes to Vivek Nagarajan, Programmer since 1987


    Using Function

    def doMywork(data):
        for i in data:
           for e in i:
             return 
    

    Using flag

    is_break = False
    for i in data:
       if is_break:
          break # outer loop break
       for e in i:
          is_break = True
          break # inner loop break
    

提交回复
热议问题