Python continue keyword

Python continue keyword allows you to control the execution of a loop based on a specific condition. When the interpreter encounters the continue statement, it jumps to the beginning of the loop, ignoring any code that follows it in the current iteration.

Unlike the break keywords that stop an iteration, continue skips the current iteration and moves to the next iteration without stopping the iteration.

In other words, it effectively aborts the current iteration and begins the next one.

This behaviour is particularly useful when you want to skip certain elements or perform specific actions only on certain conditions.

The continue keyword is used within loops, such as for and while, to skip the rest of the current iteration and move to the next iteration immediately.

Let’s consider some examples to illustrate the usage of the continue keyword.

Example 1: Skipping Even Numbers

Suppose you want to print all the odd numbers from 1 to 10, skipping the even numbers. You can easily do so using the continue keyword as shown below:

for num in range(1, 11):
    if num % 2 == 0:
        continue
    print(num)

Output:

1
3
5
7
9

In this example, when the continue statement is encountered for even numbers, it immediately skips the print(num) statement and proceeds to the next iteration.

As a result, only the odd numbers are printed.

Example 2: Skipping Specific Values

The continue keyword can also be used to skip specific values or elements within a loop. Consider a scenario where you have a list of numbers, and you want to print all the values except for a certain number, let’s say 6.

for num in range(1, 11):
    if num == 6:
        continue
    print(num)

output

1
2
3
4
5
7
8
9
10

In this example, the continue statement is triggered when the value of num is 6. It skips the subsequent print(num) statement and proceeds to the next iteration. As a result, all the numbers except 6 are printed.

Conclusion

The continue keyword in Python provides a powerful mechanism for controlling the flow of loops. It allows you to skip certain iterations based on specific conditions, making your code more concise and efficient.

By understanding and utilizing the continue statement effectively, you can streamline your loops and achieve more elegant solutions to various programming problems.

Leave a Reply

Your email address will not be published. Required fields are marked *