简体   繁体   中英

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

I am new to python and in general to programming. I am trying to combine 'while loop' with 'for loop' to iterate through some list but i am getting infinite loops. here is the 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)

similarly with this code i got the same endless loop i want an output when the condition 'lo+ l[i] is greater than 40 stops looping and gives the final 'lo'output or result. I tried every method of indentation of the print line,but could not get what i wanted. please comment on this code. 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)

Your break cancels the inner loop

this will work:

l=[0,1,2,3,4] 
stop = False
lo=0 
while( not stop):
    lo+=1 
    for i in range(len(l)):
        if not l[i]<3:
           stop = True
           break
        print(lo)

Try with this:

l=[0,1,2,3,4]
lo=0

for i in l:
    lo+=1
    if not l[i]<3:
        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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM