Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python combine 'while loop' with 'for loop' to iterate through some data

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.

like image 567
jack Avatar asked Sep 04 '25 16:09

jack


2 Answers

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)
like image 179
Jan Spurny Avatar answered Sep 07 '25 16:09

Jan Spurny


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.

like image 27
Matthias Avatar answered Sep 07 '25 16:09

Matthias