简体   繁体   中英

Infinite while loop with continue keyword

My problem - and I don't know why there is a keyword continue , which should leave the value of 3 and go further. In fact, I have a loop that is infinite - that is, it crashes the program.


tab = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
i = 0
while i < len(tab):
    print(tab[i])
    if tab[i] == 3:
        continue
    i+=1

It looks like you are trying to iterate through the list until you find a 3 then break . Do something like this:

items = [1,2,3,4,5]
for item in items:
   if item == 3:
       break

The keyword continue will pass to the next iteration of the loop, where break will stop the loop.

The continue keyword continues with the next iteration of the loop.

In your case, it prevents the statement i+=1 to be executed.

Here is what happens:

  1. Loops through 0,1,2 just fine
  2. When it evaluates tab[i] = 3 it proceeds with the next iteration of the loop and i+=1 is never executed, hence i remains 3 and never gets incremented. It keeps doing this forever.

If you want to exit the loop, you can use the break statement instead of continue .

For more information, you can read on the continue keyword here: https://docs.python.org/3/tutorial/controlflow.html

You're using the continue keyword, but I think you want break .

Your code is running forever because i never iterates past 3. Once i == 4 , it enters your if statement and continues the loop. Since it continues, it never iterates after that.

I think the answers here all assume that OP wanted to use break instead of continue .

However, if you need to use continue in a while loop, make sure you have an increment/decrement operation above the continue statement, because the continue statement jumps to the top of the while loop and, in your case, i remains 3.

Respectively, the continue statement in a do-while loop jumps to the bottom of the loop. So, in your case you have two options, either you increment above the continue or use a for-loop.

tab = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
i = -1
while i < len(tab):
    i += 1
    print(tab[i])
    if tab[i] == 3:
        continue
    

OR

for i in range(0,15):
    if i == 3:
       continue
    print(i)

Because you are using the continue keyword that skips the rest of the code. Once i reaches 3, it skips over the i+=1 command. It appears that you want to use the keyword break . You could also do:

for i in tab:
    print(i)
    if i == 3:
        break

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