Zone Of Makos

Menu icon

Using the continue statement in Python

In Python, the continue statement is used to skip the rest of the current iteration of a loop and move on to the next iteration. When the continue statement is encountered inside a loop, the loop continues with the next iteration without executing any further statements in the current iteration.

Syntax

The syntax for the continue statement in Python is as follows:

while expression:
    statement(s)
    if condition:
        continue

or:

for variable in sequence:
    statement(s)
    if condition:
        continue

Here, expression is a Boolean expression that determines whether the loop should continue, statement(s) is the body of the loop, and condition is a Boolean expression that determines whether to skip the rest of the current iteration.

Example

Let's look at an example of using the continue statement to skip over certain values in a loop:

# Program to print all even numbers in a list

numbers = [3, 7, 12, 6, 8, 9]

for num in numbers:
    if num % 2 != 0:
        continue
    print(num)

In this example, we have a list of numbers and we want to print all the even numbers in the list. We use a for loop to iterate over each number in the list, and we use an if statement to check if the current number is odd. If it is, we use the continue statement to skip the rest of the statements in the current iteration. If the current number is even, we print it.

Conclusion

The continue statement is a useful tool for skipping over certain values in a loop in Python. By using the continue statement, you can write more concise and readable code that is easier to understand and maintain.