+ 2
How to break two nested loops at the same time in python?
For Example:- for i in range(4): for j in range(1,5): if i + j == 5: break I want to stop this function once i+j is 5. But the break statement only stops one loop. How can i break both loops......???
5 Antworten
+ 9
If you put the nested loops together in a comprehension and a regular for loop, this should work (the comprehension creates number pairs and returned it as a pair of tuple). I found something similar with this principle in stack oveflow, and adapted it to this:
for pair in [(i, j) for i in range(4) for j in range(1,5)]:
print(pair) # for test only
if sum(pair) == 5:
break
An other solution could be to put the loops in a function, that can break both loops by using return.
+ 7
To add a dirty solution, put loop into try-except block.
try:
for i in range(4):
for j in range(1,5):
assert i + j != 5
except AssertionError:
pass
+ 4
You can also add the same statement to the other loop also.
Although, they are nested but they'll always be 2 loops not 1