Milind Lakhwani
Milind Lakhwani

Reputation: 23

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!

Upvotes: 0

Views: 4757

Answers (3)

Louis Lac
Louis Lac

Reputation: 6386

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

Upvotes: 5

fireball.1
fireball.1

Reputation: 1521

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

Upvotes: 1

Prasannavenkatesh
Prasannavenkatesh

Reputation: 11

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) 

Upvotes: 0

Related Questions