0

I have two for-loops in python inside while loop as follows:

while ..
  for ..
    for ..
      if condition == True:
         break

I want to break the first for-loop once the condition in the if statement is met, How can I achieve it, it appears that break is only terminating inner for loop and not outer, I want outer for-loop to be terminated.

metron
  • 201
  • 1
  • 6

3 Answers3

1

use a flag to inform outer breaker:

while ..
  for ..
    should_break = False
    for ..
      if condition == True:
         should_break = True
         break
    if should_break: break
Ariyan
  • 14,760
  • 31
  • 112
  • 175
0

I would attempt to refactor this so you don't have so many nested loops. Maybe move the inner loop into a function? Otherwise you can add the break after the inner loop as well.

while ..
  for ..
    for ..
      if condition == True:
         break
    if condition == True:
      break
ahelium
  • 86
  • 1
  • 5
0

Unfortunately, the solution I would use for C programming, a goto command (haters gonna hate), doesn't exist in Python.

I've encountered this situation as well and the best solution I know is the following:

while ...
    breakLoop = False
    for ...:
        for ...:
            if condition:
                breakLoop = True
                break
        if breakLoop:
            break
Daniel Walker
  • 6,380
  • 5
  • 22
  • 45