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?
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?
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
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')
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