Introduction to the Python Continue Statement
In Python, the continue statement is used to control the flow of a loop. It allows you to skip the rest of the code inside a loop and move on to the next iteration. This can be useful when you want to skip certain iterations or when you need to perform some conditional checks before continuing with the loop.
Syntax of the Continue Statement
The syntax of the continue statement in Python is as follows:
while condition: # code block if condition: continue # code block
or
for item in sequence: # code block if condition: continue # code block
Examples of the Python Continue Statement
Let’s explore some examples to understand how the continue statement works in different scenarios.
Example 1: Skipping Odd Numbers
for num in range(1, 11): if num % 2 == 1: continue print(num)
In this example, the continue statement is used to skip odd numbers. The range() function generates numbers from 1 to 10, and the if condition checks if the number is odd using the modulo operator (%). If the condition is true, the continue statement is executed, and the loop moves on to the next iteration without printing the odd number. If the condition is false, the number is printed.
The output of this example will be:
2 4 6 8 10
Example 2: Skipping Specific Values
fruits = ["apple", "banana", "cherry", "date", "elderberry"] for fruit in fruits: if fruit == "cherry": continue print(fruit)
In this example, the continue statement is used to skip the value “cherry” in the list of fruits. The for loop iterates over each fruit in the list, and the if condition checks if the fruit is equal to “cherry”. If the condition is true, the continue statement is executed, and the loop moves on to the next iteration without printing “cherry”. If the condition is false, the fruit is printed.
The output of this example will be:
apple banana date elderberry
Example 3: Conditional Check with Continue
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for num in numbers: if num % 2 == 0: print(f"{num} is even") continue print(f"{num} is odd")
In this example, the continue statement is used to perform a conditional check and continue with the loop accordingly. The for loop iterates over each number in the list, and the if condition checks if the number is even using the modulo operator (%). If the condition is true, the message “{num} is even” is printed, and the loop moves on to the next iteration. If the condition is false, the message “{num} is odd” is printed.
The output of this example will be:
1 is odd 2 is even 3 is odd 4 is even 5 is odd 6 is even 7 is odd 8 is even 9 is odd 10 is even
Conclusion
The continue statement in Python provides a convenient way to control the flow of a loop. It allows you to skip certain iterations based on specific conditions, making your code more efficient and concise. By understanding how to use the continue statement, you can simplify loop control and achieve more effective programming solutions.