How to break out of multiple loops?

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

    My reason for coming here is that i had an outer loop and an inner loop like so:

    for x in array:
      for y in dont_use_these_values:
        if x.value==y:
          array.remove(x)  # fixed, was array.pop(x) in my original answer
          continue
    
      do some other stuff with x
    

    As you can see, it won't actually go to the next x, but will go to the next y instead.

    what i found to solve this simply was to run through the array twice instead:

    for x in array:
      for y in dont_use_these_values:
        if x.value==y:
          array.remove(x)  # fixed, was array.pop(x) in my original answer
          continue
    
    for x in array:
      do some other stuff with x
    

    I know this was a specific case of OP's question, but I am posting it in the hope that it will help someone think about their problem differently while keeping things simple.

提交回复
热议问题