Search code examples
pythonwhile-loopbreakcontinue

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!


Solution

  • The continue statement ignores the rest of the loop and returns back to the top. The count value is never updated since the count += 1 statement is after continue ignored, thus 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