what is the difference between these sets of loops?
for i in range(0,5):
print i,'i'
for x in range(0,4):
print x,'x'
break
AND
for i in range(0,5):
print i,'i'
for x in range(0,4):
print x,'x'
break
what's the scope of break statement?
A break
will only break out of the inner-most loop it's inside of. Your first example breaks from the outer loop, the second example only breaks out of the inner loop.
To break out of multiple loops you need use a variable to keep track of whether you're trying to exit and check it each time the parent loop occurs.
is_looping = True
for i in range(5): # outer loop
for x in range(4): # inner loop
if x == 2:
is_looping = False
break # break out of the inner loop
if not is_looping:
break # break out of outer loop
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