How to break while loop in an inner for loop in python?
Solution 1
Until the inner loop "returns", the condition in the outer loop will never be re-examinated. If you need this check to happen every time after i
changes, do this instead:
while i<=10:
for a in xrange(1, x+1):
print "ok"
i+=1
if i > 10:
break
That break
will only exit the inner loop, but since the outer loop condition will evaluate to False
, it will exit that too.
Solution 2
i = 0
x = 100
def do_my_loops():
while i<=10:
for a in xrange(1, x+1):
print "ok"
i+=1
if time_to_break:
return
do_my_loops()
where time_to_break
is the condition you're checking.
Or in general:
def loop_container():
outer_loop:
inner_loop:
if done:
return
loop_container()
Solution 3
The problem is that the outer loop's condition won't be checked until the inner loop finishes - and at this point i
is already 100. From my perspective, the correct way to write this and get the desired output would be to put a guard inside the inner loop and break it when i
reaches 10.
for a in xrange(1, x+1):
if i < 10:
print "ok"
i+=1
else:
break
If there is some other reason why you want to break an outer loop while you're inside the inner loop, maybe you should let us in on the details to better understand it.
alwbtc
Updated on June 05, 2022Comments
-
alwbtc almost 2 years
while
doesn't break when i>10 in for loop:i = 0 x = 100 while i<=10: for a in xrange(1, x+1): print "ok" i+=1
and it prints
"ok"
100 times. How to break thewhile
loop wheni
reaches 10 infor
loop? -
Matt Briançon over 11 yearsJust be sure not to add anything after the for loop or that will execute after the inner loop breaks.
-
alwbtc over 11 years@Matt Briançon Yes?? I thought
while
will break as soon asfor
breaks? -
mgibsonbr over 11 years@alwbtc
while
won't break unless either of these happens: a) you callbreak
while in its body (strictly in its body, not in the loops inside it); b) the body finished executing, and the condition evaluates toFalse
; c) you callcontinue
while in its body (strictly, also) and the condition evaluates toFalse
.