Complete Guide to Using the continue Statement in Python | Master Loop Control

1. Understanding the Basics of the continue Statement

The continue statement is used in Python loops to skip the current iteration when a certain condition is met and move on to the next iteration. This is useful when you want to exclude specific elements from processing.

1.1 Basic Syntax of continue

The continue statement can be used inside a for loop or a while loop. The basic syntax is as follows:

for i in range(5):
    if i == 2:
        continue
    print(i)

In this code, when i is 2, the continue statement is executed, skipping the print statement. As a result, the output will be 0, 1, 3, 4.

2. Using continue in a for Loop

The for loop is commonly used for iterative processing. Using continue within a for loop allows you to skip specific iterations based on certain conditions.

2.1 Basic Example of continue in a for Loop

The following code iterates through a list of numbers and skips processing for certain values based on a condition.

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num % 2 == 0:
        continue
    print(num)

In this code, even numbers are skipped using continue, so the output will be 1, 3, 5.

2.2 Using continue in Nested for Loops

When using continue in nested loops, it only affects the innermost loop. For example:

for i in range(3):
    for j in range(3):
        if j == 1:
            continue
        print(i, j)

In this code, when j is 1, the continue statement skips the iteration, so the output will be (0, 0), (0, 2), (1, 0), (1, 2), (2, 0), (2, 2).

侍エンジニア塾

3. Using continue in a while Loop

Similarly, the continue statement can be used in a while loop to skip the current iteration and move on to the next one.

3.1 Basic Example of continue in a while Loop

The following code takes user input and skips processing under a specific condition.

counter = 0
while counter < 5:
    counter += 1
    if counter == 3:
        continue
    print(counter)

Here, when counter is 3, the continue statement is executed, skipping the print statement. The output will be 1, 2, 4, 5.

3.2 Input Validation with while Loops

The continue statement is also useful for input validation in while loops. For example, you can use continue to skip empty inputs:

while True:
    text = input("Enter a number (or 'exit' to quit): ")
    if text == 'exit':
        break
    if text == '':
        print("Empty input, please try again.")
        continue
    print(f"You entered: {text}")

In this code, if the user enters an empty input, the continue statement skips the rest of the loop and prompts the user again.

4. Combining continue with else in Loops

In Python, both for and while loops can have an else block. Even if continue is used inside the loop, the else block will still execute when the loop completes.

4.1 Example Using else with continue

The following example demonstrates how the else block runs even when continue is used in the loop.

for i in range(3):
    for j in range(3):
        if j == 1:
            continue
        print(i, j)
    else:
        print("Inner loop finished.")

In this code, even though continue is used to skip certain iterations, the else block will still execute after the inner loop completes.

5. Difference Between continue and break

Both continue and break control the flow of loops, but they serve different purposes.

5.1 How continue Works

The continue statement skips the current iteration and moves on to the next iteration without terminating the loop.

5.2 How break Works

On the other hand, the break statement completely exits the loop when a specified condition is met. Let's compare them with an example:

for i in range(5):
    if i == 3:
        break
    print(i)

In this code, when i reaches 3, the break statement is executed, ending the loop entirely. The output will be 0, 1, 2.

5.3 When to Use continue vs. break

Use continue when you want to skip specific iterations but keep the loop running. Use break when you want to completely terminate the loop.

6. Practical Applications

The continue statement is useful in real-world programming for writing efficient code and avoiding unnecessary processing.

6.1 Filtering Data

For example, you can use continue to exclude certain values from a dataset.

data = [1, -1, 2, -2, 3, -3]
for value in data:
    if value < 0:
        continue
    print(value)

In this code, negative values are skipped, so the output will be 1, 2, 3.

RUNTEQ(ランテック)|超実戦型エンジニア育成スクール

7. Common Mistakes and Troubleshooting

Here are some common mistakes when using the continue statement and how to avoid them.

7.1 Indentation Errors

One of the most common mistakes when using continue is incorrect indentation. If continue is not properly indented, it can cause unexpected behavior.

7.2 Risk of Infinite Loops

When using continue in a while loop, you must ensure that the loop progresses properly. If you forget to update the loop variable before continue, the loop may become infinite.

counter = 0
while counter < 5:
    if counter == 3:
        continue  # This will cause an infinite loop
    counter += 1
    print(counter)

In this code, since counter is not updated before continue, the loop gets stuck in an infinite cycle.

8. Conclusion

The continue statement is a powerful tool for controlling loops in Python. It helps make code more efficient by skipping unnecessary processing. Understanding when to use continue versus break and avoiding common mistakes will make your Python programming more effective.