How to break nested loops in Python | Sololearn: Learn to code for FREE!

+12

How to break nested loops in Python

If there are two loops in which one loop is inside another loop.So how can i can both loop at once condition.

6/25/2018 4:24:54 AM

Adarsh Srivastava

16 Answers

New Answer

+34

Adarsh Srivastava here is solution. for i in range(0,6): for z in range(0,6): if(z==2): break #break inner loop. else: print(z) if(z==2): break #break outer loop.

+5

Maninder Singh thanku very much ..

+3

I would recommend checking out this Stackoverflow question on this as some of the answers explain how to do so quite well - https://stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops-in-python

+1

Rosy can you please add your clear code here?

+1

var = False while '''condition''': #do smth while '''condition''': #do smth if '''you need to break the loop''': var = True break if var: #or 'if var == True', no difference break

+1

for i in range (0,n): for j in range (0, m): break # Exit nested loops

+1

stop = False pip = [ 100, 200, 300] while not(stop) : for x in pip : if x < 300 : print("lower") else : print("higher") stop = True (that to break while loop ) break functions can be used in state of the variable (stop) to break: (1) all the loop : remove stop variable , add break in the last of code outside for loop and inside while loop . (2) for loop only : remove stop variable , add break in the last of code inside for loop . the first way make code complicate. the second way make it more clearer . use DRY principle .

0

✅ refactor the nested loop into a function and use return to break out .

0

I still did not manage to skip the even number in the fizzbuzz code challenge, can someone explain to me how to break the loop without stopping after 1

0

You need to use the 'continue' operator to skip everything that is written in the loop after it and go straight to the next iteration of the loop.

0

We can skip the even numbers by given range(1,n,2)

0

var = False while '''condition''': #do smth while '''condition''': #do smth if '''you need to break the loop''': var = True break if var: #or 'if var == True', no difference break

0

for i in range(0,6): for z in range(0,6): print(i) Why the output is 0 0 0 0 0 0 1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3 4 4 4 4 4 4 5 5 5 5 5 5 6 6 6 6 6 6 6

0

This can be done by using "break" keyword

0

for i in range(1, 10): if i == 5: # when i is 5 exit the loop break print("i =", i) print("break out")

0

Use break statement