python combine 'while loop' with 'for loop' to iterate through some data
Solution 1
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)
Solution 2
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.
Related videos on Youtube
jack
Updated on June 04, 2022Comments
-
jack almost 2 years
I am trying to combine a
while
loop with afor
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 finallo
output as result. I tried every method of indentation of the print line, but could not get what I wanted. Thanks in advance.-
Chris over 9 yearsTry go trough in on paper, step by step and you will see what really happens, or add logs/prints to see what happens in each step.
-
Jamie Cockburn over 9 yearsIt's not really clear what you are trying to achieve. What output do you want?
-
Mike Vella over 9 yearsYou should always try and avoid breaks, they make code generally harder to understand.
-
jack over 9 yearsi am trying to get the lo output as the l[i]>3 condition is not met.
-