简体   繁体   中英

Continue statement in while loop python

I am a beginner in python and I am having trouble with this code:

count = 0

while count <15:
   if count == 5:
      continue
   print(count)
   count += 1

When the value of count = 5 it stops the loop as if there was a break statement. Why is it so? Please help!

The continue statement ignores the rest of the loop and returns back to the top. The count is never updated as the count += 1 is ignored so from this point count is always 5 and the continue statement is always executed. The print statement is also never executed past 4.

It does not break the loop, the loop is still running.

count = 0

while count <15:
  if count == 5:
    continue

  # The following is ignored after count = 4
  print(count)
  count += 1

I think you need to use a pass statement instead of continue and change your indentation (this is assuming you want to print numbers from 0-15 but not 5).

pass is the equivalent of doing nothing

count = 0

while count <15:
   if count == 5:
      pass
   else:
      print(count)
   count += 1

continue takes the code to the end of the loop. This means that when count is 5, the loop goes to the end and the value of count never increments and gets stuck in an infinite loop.

Take a look at break, pass and continue statements

The continue statement in Python returns the control to the beginning of the current loop. When encountered, the loop starts next iteration without executing the remaining statements in the current iteration. When count becomes 5 in your loop it remains 5 since the loop is returned to the start without incrementing count.The following code may help you get it:

count = 0
while count < 15 :
   count += 1
   if count == 5 :
     continue 
print(count) 

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