ScanSkill

continue

This continue statement is used to skip the execution of the code below it and starts a new cycle of the loop.

Syntax

loop:
    continue
else:
    statement(s)

Here,

  • loop: Either of for or while loop.
  • statement(s): Block of code to be executed.
  • else: Optional. Used to indicate the block of code to be executed when the loop terminates without break statement.

Note: The continue statement can only appear in a loop body. It causes the rest of the statement body in the loop to be skipped.

A continue statement executed in the first suite skips the rest of the statemen(s) and continues with the next item, or with the else clause if there was no next item.

Examples

  • With for loop
>>> for i in range(5):
...     if i == 3:
...         continue
...     print i
...
0
1
2
4
  • With while loop
>>> i = 0
>>> while i < 3:
...     i += 1
...     if i == 2:
...         continue
...     print(i)
... 
1
3
  • With else condition
>>> i = 0
>>> while i < 3:
...     i += 1
...     if i == 2:
...         continue
...     print(i)
... else:
...     print("break")
... 
1
3
break
>>> i = 0
>>> while i < 3:
...     i += 1
...     if i == 2:
...         continue
...     print(i)
...     break
... else:
...     print("break")
... 
1

Here, since break is used, else will not be executed. So the loop will be terminated.