I am trying to combine a while
loop with a for
loop to iterate through some list but I am getting infinite loops. My code:
l=[0,2,3,4]
lo=0
for i in range(len(l)):
while (True):
lo+=1
if lo+l[i]>40:
break
print(lo)
This code results in an endless loop. I want an output when the condition lo+ l[i]
is greater than 40; it should stop looping and print the final lo
output as result. I tried every method of indentation of the print line, but could not get what I wanted. Thanks in advance.
You get infinite loop because you wrote the infinite loop. You've probably thought that the break
statement will somehow "magically" know that you don't want to end just the for loop, but also the while loop. But break
will always break only one loop - the innermost one. So that means that your code actually does this:
while (True): # <- infinite while loop
lo += 1
for i in range(len(l)): # <- for loop
if not l[i] < 3:
break # <- break the for loop
print(lo)
# while loop continues
If you want to end both loops, you have to do it explicitly - for example, you can use a boolean variable:
keep_running = True
while (keep_running):
lo += 1
for i in range(len(l)):
if not l[i] < 3:
# this will effectively
# stop the while loop:
keep_running = False
break
print(lo)
You don't need the external infinite loop and you don't have to manage the index yourself (see enumerate in the documentation).
l = [0,1,2,3,4]
for index, value in enumerate(l):
if value >= 3:
break
print(index)
I changed the condition if value not < 3:
to if value >= 3:
for improved readability.
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