The continue statement in Python is used to skip the rest of the code inside a loop for the current iteration and jump to the next iteration of the loop. This is useful when you want to bypass certain parts of the loop's code based on a condition and continue with the next iteration.
#loop statements
continue
1. In a for Loop
The continue statement can be used to skip the rest of the code inside the for loop for the current iteration and proceed with the next iteration.
for i in range(10):
if i % 2 == 0:
continue # Skip the rest of the loop for even
numbers
print(i)
1
3
5
7
9
In this example, the continue statement skips printing the even numbers, so only odd numbers are printed.
Similarly, the continue statement can be used in a while loop to skip the remaining code inside the loop and proceed to the next iteration.
i = 0
while i < 10:
if i % 2 == 0:
i += 1
continue # Skip the rest of the loop for even
numbers
print(i)
i += 1
1
3
5
7
9
Here, the continue statement skips printing even numbers, and the loop continues with the next iteration.
The continue statement cannot be used directly in list comprehensions. However, you can achieve similar functionality by using conditional expressions.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
oddNumbers = [num for num in numbers if num % 2 != 0]
print(oddNumbers)
[1, 3, 5, 7, 9]
This example filters out even numbers, leaving only odd numbers in the resulting list.
The continue and pass keywords in Python serve different purposes and are used in different contexts.
| Heading | continue | pass |
|---|---|---|
| Definition | The continue statement skips the remaining statements in the current iteration of a loop and proceeds to the next iteration. | The pass keyword is a null operation used to indicate that no action is to be taken. |
| Action | Takes control back to the start of the loop. | Performs no action; it is essentially a placeholder. |
| Application | Works within for and while loops to control iteration flow. | Used where code is syntactically required but where no action is needed. |
| Syntax | continue | pass |
| Interpretation | Used within loops to alter control flow. | Removed during the byte-compile stage; serves as a placeholder. |