Python Continue Statement

In Python, the continue statement is used to alter the flow of control in a loop. When you use the continue statement within a loop, it causes the current iteration of the loop to be terminated immediately, and the loop proceeds to the next iteration. This can be useful when you want to skip a part of the loop's code and move to the next iteration without completing the current one.

Here's the basic syntax of the continue statement:

        
for variable in sequence:
    # Code before the continue statement
    if condition:
        continue  # Skip the rest of the current iteration and move to the next iteration
    # Code after the continue statement
        
    

Now, let's look at an example to illustrate how the continue statement works:

        
# Example: Using the continue statement to skip even numbers in a loop

for number in range(1, 11):
    if number % 2 == 0:
        print(f"Skipping even number: {number}")
        continue  # Skip the even numbers

    print(f"Processing odd number: {number}")

print("Loop finished.")
        
    

In this example, we use a for loop to iterate through the numbers from 1 to 10. When the if condition checks whether a number is even (divisible by 2), and if it is even, the continue statement is executed, which skips the rest of the code in that iteration and moves to the next number. This way, even numbers are skipped, and odd numbers are processed.

In the output, you can see that even numbers are marked as "Skipping even number," and odd numbers are marked as "Processing odd number." After the loop is finished, the message "Loop finished" is printed.

The continue statement is a handy tool for controlling the flow of your loops when certain conditions need to be met to continue or skip iterations.