1
inc = 0
for i in range(100):
  for j in range(5):  
    print("before",inc)
    inc = inc + 1
    print("after",inc)
    if inc == 1:
      break

This is the minimum code. I want to break the all the loops at once and yes I do know a method that I found on this site the method I found

inc = 0
done = None
for i in range(100):
  for j in range(5):  
    print("before",inc)
    inc = inc + 1
    print("after",inc)
    if inc == 1:
      done = True
      break
  if done:
    break

But the above method would be too long and tedious if there is a more than 4 loops or code is a bit more complex. Is there a function/library that can help?

1 Answers1

1

use else in the inner loop - If the inner for loop breaks the else will not be executed and the outer loop will break and vice-versa

inc = 0
for _ in range(100):
    for _ in range(5):  
        print("before",inc)
        inc += 1
        print("after",inc)
        if inc == 1:
            break
    else:
        continue 
    break
Nk03
  • 14,699
  • 2
  • 8
  • 22