Python | Loops | Continue Statement

The continue statement ignores everything is after it in the loop and begins execution of the loop again from the beginning. Let’s modify the hello.py file to look like it is shown below:

count = 10
print('The countdown is about to begin')
while (count >= 0):
	if (count == 0):
		print('the end')
	else:
		print(count)	
	if (count == 6):
		count = 3
		continue	
	count -= 1

Continue Statement in Python

So, we have the variable count that has a value of 10. The while statement starts the loop. The if after it says that when the count is 0 the message “the end” will be printed on the screen.

There is another if statement which says that when count is 6 to make it 3 (the continue statement does that) and continue the loop with the value of count to be 3.

If you take a look at the above picture you see that the numbers 5 and 4 are missing.

The next example uses continue to skip odd numbers. This code prints all even numbers less than 10 and greater than or equal to 0.

>>> a = 10
>>> while a:
...     a = a - 1
...     if a % 2 != 0: continue
...     print(a, end = ' | ')
... 
8 | 6 | 4 | 2 | 0 | >>>

You could achieve the same result without using continue.

>>> a = 10
>>> while a:
...     a = a - 1
...     if a % 2 == 0:
...             print (a, end = ' | ')
... 
8 | 6 | 4 | 2 | 0 | >>> 

Leave a Reply