Table of Contents
ToggleThe Python `continue` statement is used to skip the current iteration of a loop and jump to the next iteration. It’s often used in scenarios where certain conditions need to be checked and you want to avoid executing the rest of the loop body for those cases. Let’s explore this concept in detail with code examples and real-world use cases.
The `continue` statement allows you to skip the current iteration of the loop and move to the next one. When the `continue` statement is executed, the remaining part of the loop body is skipped, and the next iteration begins immediately. It’s often used to filter out unwanted values during iteration without stopping the entire loop, unlike the `break` statement, which completely exits the loop.
looping_statement:
condition_check:
continue
In this syntax, the `continue` statement is used inside the loop. When the condition (`condition_check`) evaluates to true, the `continue` statement is executed, and the loop moves to the next iteration, skipping the code below it in the loop.
In this example, we iterate through the string `’Python’` and skip the character `’h’` using the `continue` statement. As soon as the letter `’h’` is encountered, it is skipped, and the loop continues to the next character.
for letter in 'Python':
if letter == 'h':
continue
print('Current Letter:', letter)
When this code is executed, the output will be:
Current Letter: P
Current Letter: y
Current Letter: t
Current Letter: o
Current Letter: n
Here, we use the `continue` statement in a while loop to check and print the prime factors of a number. The code skips any non-prime factors and proceeds with the next iteration until the number is reduced to 1.
num = 60
d = 2
while num > 1:
if num % d == 0:
print(d)
num = num / d
continue
d = d + 1
This will output the prime factors of 60:
Prime factors for: 60
2
2
3
5
In nested loops, the `continue` statement works within the inner loop. When it is encountered in the inner loop, it will skip the current iteration of that loop and continue with the next iteration of the inner loop, while the outer loop continues executing.
numbers = [11, 33, 55, 39, 55, 75, 37, 21, 23, 41, 13]
for num in numbers:
if num == 33:
print("Found the number:", num)
continue
print("Processing number:", num)
In the example above, the number 33 will trigger the `continue` statement, skipping the rest of the code and moving to the next iteration.
The `continue` statement is a powerful tool in Python that allows you to control the flow of loops. By skipping specific iterations based on conditions, you can make your code more efficient and clear. This functionality is useful in situations where you need to filter out unwanted values or perform specific actions only when certain conditions are met. Understanding and using `continue` effectively can make your Python programs more concise and readable.
