-1
x = 10
f1:
for i in range(x):
    for j in range(x):
        print(j)
        if j == 6:
            break f1

1.How to break from outer loop in python?

U12-Forward
  • 65,118
  • 12
  • 70
  • 89

3 Answers3

0

As can be seen from your code, you do not need 2 loops or break using labels. You can simply do

for i in range(10):
  print(i)
  if i == 6:
    break

The first time i loop executes, j loop executes. As soon as j reaches 6, i loop has to be exitted. So, what is the point of 2 loops or breaking? Still if you want for similar problems, you can try raising a StopIteration exception. Try

try:
    x = 10
    for i in range(x):
        for j in range(x):
            print(j)
            if j == 6:
                raise StopIteration
except StopIteration:
    print('Execution done')

This prints

0
1
2
3
4
5
6
Execution done
Swati Srivastava
  • 992
  • 1
  • 10
  • 16
  • used flags as it looks simple and familiar x = 10 for i in range(x): flag = False for j in range(x): print(j) if j == 6: flag = True break if flag: break print(i) print('Execution done') Thanks :) – user3529017 Feb 13 '20 at 12:39
  • Using flags is also a good way of solving the problem. Glad your issue got resolved. – Swati Srivastava Feb 14 '20 at 16:41
0

You can use a return statement if the loops are in the context of a function. like in the example below. Alternatively the raising an exceptionwill effectively stop the outer loop.

>>> def doit():
...   for i in range(0,10):
...     for j in range(10,20):
...       print(i,j)
...       if j==12:
...         return
...
>>> doit()
0 10
0 11
0 12
  • used flag as it looks simple and familiar x = 10 for i in range(x): flag = False for j in range(x): print(j) if j == 6: flag = True break if flag: break print(i) print('Execution done') – user3529017 Feb 13 '20 at 12:38
0

I DID THIS

x = 10
for i in range(x):
    flag = False
    for j in range(x):
        print(j)
        if j == 6:
            flag = True
            break
    if flag:
        break
    print(i)
print('Execution done')