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?

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
Aamir
  • 2,380
  • 3
  • 24
  • 54

3 Answers3

1

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
  • 1,102
  • 1
  • 12
  • 18
  • 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 :) – Aamir 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
1

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 completed')
Aamir
  • 2,380
  • 3
  • 24
  • 54
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
  • 1
    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') – Aamir Feb 13 '20 at 12:38