0

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!

2
  • 2
    The code you posted doesn't match the behaviour you describe. Commented Apr 22, 2020 at 8:45
  • 4
    It does not stop, it becomes an infinite loop, since count is no longer updated. It just stops printing stuff. Commented Apr 22, 2020 at 8:45

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.