
Python Continue
The Python, the continue
statement is used to skip the current iteration of a loop (either a for
loop or a while
loop) and proceed to the next iteration. It allows you to bypass the remaining code inside the loop for the current iteration and jump to the next iteration of the loop.
The basic syntax of the continue
statement is as follows:
while condition:
# Code before the continue statement
if some_condition:
continue
# Code after the continue statement
Here’s how the continue
statement works:
- The
while
orfor
loop begins executing as long as the specifiedcondition
remainsTrue
. - Within the loop, you can use the
continue
statement when a specific condition (some_condition
) is met. - When the
continue
statement is encountered, the loop skips the remaining code for the current iteration and immediately proceeds to the next iteration.
Here are a few examples of how the continue
statement can be used:
Example 1: Skipping Even Numbers
for number in range(1, 11):
if number % 2 == 0:
continue
print(number)
In this example, the for
loop iterates through the numbers from 1 to 10. When it encounters an even number (i.e., a number divisible by 2), the continue
statement is used to skip printing that number, and the loop proceeds to the next iteration.
Output:
1
3
5
7
9
Example 2: Skipping Specific Items in a List
fruits = ["apple", "banana", "cherry", "date", "fig"]
for fruit in fruits:
if fruit == "date":
continue
print(fruit)
In this example, the for
loop iterates through a list of fruits. When it encounters the fruit “date,” the continue
statement is used to skip printing that fruit, and the loop proceeds to the next iteration.
Output:
apple
banana
cherry
fig
Example 3: Skipping Rows in CSV Data
csv_data = [
["Name", "Age", "City"],
["Alice", 25, "New York"],
["Bob", 32, "Los Angeles"],
["Carol", 28, "Chicago"],
]
for row in csv_data:
if "Bob" in row:
continue
print(row)
In this example, the for
loop iterates through a list of CSV data rows. When it encounters a row containing the name “Bob,” the continue
statement is used to skip printing that row, and the loop proceeds to the next iteration.
Output:
['Name', 'Age', 'City']
['Alice', 25, 'New York']
['Carol', 28, 'Chicago']
The continue
statement is a useful tool for controlling the flow of loops in Python when you want to skip certain iterations based on specific conditions. It allows you to customize the behavior of your loops and skip over items or sections of code as needed.