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 the while
loop when i
reaches 10 in for
loop?
The break statement exits a for or while loop completely. To skip the rest of the instructions in the loop and begin the next iteration, use a continue statement. break is not defined outside a for or while loop.
Python provides two keywords that terminate a loop iteration prematurely: The Python break statement immediately terminates a loop entirely. Program execution proceeds to the first statement following the loop body. The Python continue statement immediately terminates the current loop iteration.
Method 3: Using a flag variable The if block must check the value of the flag variable and contain a break statement. If the flag variable is True, then the if block will be executed and will break out of the inner loop also. Else, the outer loop will continue.
The break keyword is helpful for single loops, and we can use labeled breaks for nested loops.
Until the inner loop "returns", the condition in the outer loop will never be re-examined. 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.
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With