Continue Statement in Python
In Python, the continue statement allows you to skip the current iteration of a loop and move directly to the next one.
continue
Unlike the break statement, continue doesn't completely exit the loop but rather stops the current iteration prematurely, allowing the next iteration to begin in both for and while loops.
Practical Examples
Example 1 (for loop)
This script performs seven iterations (from 1 to 7) using a FOR loop.
The loop includes a print statement that outputs the current loop number to the screen.
- for i in range(1, 8):
- if i == 5: continue
- print(i)
During the fifth iteration, the IF statement triggers the continue instruction, which skips this iteration and returns control to the FOR loop to start the sixth iteration.
As a result, the script's output is:
1
2
3
4
6
7
The number 5 is missing from the output because the fifth iteration was skipped by the continue statement before the print(i) statement could execute.
Example 2 (while loop)
This script performs the same operation as the previous example, but using a while loop.
- i = 0
- while i < 7:
- i += 1
- if i == 5: continue
- print(i)
In the fifth iteration, the continue statement skips the current iteration and proceeds to the next one.
The output of this script is:
1
2
3
4
6
7
Again, the number 5 is missing because the iteration was skipped before completing.
And so on.