I have to execute a for loop to traverse a list that resides inside a while loop like the following example:
while True:
for i in range(0, 100):
if i > 50:
break
print(i)
The problem I’m facing right now is that break instruction only stops the execution of the for loop, leaving the infinite while True always reach the print(i) line. So my question is, how can I add an instruction like break to close both while and for loops? And if there would be more than 2 nested loops, how could this be done?
The output of the last example is:
51
51
51
51
51
51
51
51
51
51
...
The desired functioning of the "break" line would lead to a null input for that example, which is the correct solution the code should give. The main goal here is to substitute break with an appropriate instruction to perform loop exiting.
>Solution :
I’d use a variable for that. Like this
run = True
while run:
for i in range(0, 100):
if i > 50:
run = False
break
print(i)
— EDIT —
Even if above works, the highest ranked solution on How can I break out of multiple loops? is more elegant.
while True:
for i in range(0, 100):
if i > 50:
break
else:
continue
print(i)
break