17
How to break outer ones of nested loops in Python?
You may have faced something weird in Python!
Consider you would use two nested loops. Just use break
keyword in the most internal one. What happens? Only the internal one would be broken and stop working. What about the others? Well, Python doesn't have any elegant way for doing this. I'll tell you how to deal with it.
Run the code below:
for i in range(10):
for j in range(10):
if j == 4:
print(j)
break
You would see number four 10 times. But...
Sometimes the inner loops depend on outer ones. Therefore you need to stop outer ones when conditions are provided in inner ones.
The most easy way for solving the problem is using flags.
Check the code below:
loop_breaker = False
for i in range(10):
if loop_breaker:
break
for j in range(10):
if j == 4:
print(j)
loop_breaker = True
break
BOOM! It prints number four only 1 time.
Use and enjoy!
17