In this Python tutorial, we will learn about continue statement, and how to use this continue statement to proceed with the next iteration of a For loop, While loop, etc., with examples.
Python continue
Python continue is a loop control statement.
Python continue is used to skip further statements in a loop, and continue with the further iterations of the loop.
Syntax of continue statement
Following is the syntax of Python continue statement.
continue
Examples
1. continue statement in For loop
In the following example, we will use continue statement inside Python For loop to skip the statements inside the loop for this iterationand continue with the rest of iterations.
Python Program
for number in [1, 2, 3, 5, 6, 10, 11, 12]:
if number==6:
continue
print(number)
print('Bye')
Output
1
2
3
5
10
11
12
Bye
Only those statements that are after continue statement inside the loop are skipped for that specific iteration and continued with subsequent iterations.
2. continue statement in while loop
In the following example, we will use continue statement inside Python While Loop.
Python Program
i=1
while i < 11:
if i==6:
i=i+1
continue
print(i)
i=i+1
print('Bye')
Output
1
2
3
4
5
7
8
9
10
Bye
Be careful with the update before continue statement. It may result in infinite loop.
3. continue statement outside loop
In the following example, we will try to use continue statement outside for or while loop statement.
Python Program
i=1
if i==2:
continue
print('Bye')
Output
File "example1.py", line 4
continue
^
SyntaxError: 'continue' not properly in loop
You will get SyntaxError
with the message 'continue' not properly in loop
if you try to use continue statement outside for or while loop.
Conclusion
In this Python Tutorial, we learned how to use Python continue statement with for and while loops.