Continue the loop in Python


With the continue statement we can stop the current iteration of the loop, and continue with the next.

When Python hits continue, it skips (not execute) any code left, and jumps directly to the next iteration instead.

In this example, we will not let anyone inside a bar if their age is less than 21:

ages = [10, 30, 21, 19, 25]

for age in ages:
	if age < 21:
		continue
	print(f"Someone of age {age} entered the bar")

The output of this program is:

Someone of age 30 entered the bar
Someone of age 21 entered the bar
Someone of age 25 entered the bar

As you can see, our program doesn't print for ages 10 and 19.

Here's what happens during this loop:

1. First iteration:
	a. age = 10
	b. Is age < 21? Yes:
	    continue => Go directly to the next age
	
2. Second iteration:
	a. age = 30
	b. Is age < 21? No.
	c. print
	
3. Third iteration:
	a. age = 21
	b. Is age < 21? No.
	c. print

4. Forth iteration:
	a. age = 19
	b. Is age < 21? Yes:
	    continue => Go directly to the next age
      
5. Fifth iteration:
	a. age = 25
	b. Is age < 21? No.
	c. print

Assignment
Let's allow only the people with height at least 170 into the arena.


Hint
Look at the examples above if you get stuck.


Introduction

The continue statement in Python is a control flow statement that allows you to skip the rest of the code inside a loop for the current iteration only. Looping is a fundamental concept in programming, and understanding how to control the flow of loops is crucial for writing efficient and effective code. The continue statement is particularly useful in scenarios where you need to skip certain iterations based on a condition.

Understanding the Basics

The continue statement is used inside loops to skip the current iteration and proceed to the next iteration. This is useful when you want to ignore certain values or conditions without breaking out of the loop entirely. Here's a simple example to illustrate:

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

In this example, the loop will skip printing even numbers and only print odd numbers.

Main Concepts

The key concept here is the use of the continue statement to control the flow of the loop. When the continue statement is encountered, the loop immediately jumps to the next iteration, skipping any code that follows it within the loop. This can be particularly useful for filtering data or handling specific conditions within a loop.

Examples and Use Cases

Let's look at a few examples to understand how the continue statement can be applied in different contexts:

# Example 1: Skipping negative numbers
numbers = [-1, 2, -3, 4, -5]
for number in numbers:
    if number < 0:
        continue
    print(number)

# Example 2: Skipping specific characters in a string
text = "hello world"
for char in text:
    if char in "aeiou":
        continue
    print(char, end="")

In the first example, the loop skips negative numbers and only prints positive numbers. In the second example, the loop skips vowels and prints the rest of the characters in the string.

Common Pitfalls and Best Practices

One common mistake when using the continue statement is forgetting that it only skips the current iteration, not the entire loop. Another pitfall is overusing continue, which can make the code harder to read and maintain. Here are some best practices:

Advanced Techniques

In more advanced scenarios, you might combine the continue statement with other control flow statements like break and else clauses in loops. For example:

numbers = [1, 2, 3, 4, 5]
for number in numbers:
    if number % 2 == 0:
        continue
    if number > 3:
        break
    print(number)
else:
    print("Loop completed without break")

In this example, the loop will skip even numbers and stop if a number greater than 3 is encountered. The else clause will execute only if the loop completes without encountering a break statement.

Code Implementation

Let's implement the assignment where we allow only people with a height of at least 170 cm into the arena:

heights = [160, 175, 168, 180, 172]

for height in heights:
    # If height is less than 170, skip this iteration
    if height < 170:
        continue
    print(f"Someone with height {height} cm entered the arena")

In this code, we iterate over a list of heights and use the continue statement to skip any height that is less than 170 cm.

Debugging and Testing

When debugging code that uses the continue statement, it's important to ensure that the conditions for skipping iterations are correct. You can use print statements or a debugger to check the flow of the loop. For testing, you can write test cases to verify that the loop behaves as expected:

def test_heights():
    heights = [160, 175, 168, 180, 172]
    allowed_heights = []
    for height in heights:
        if height < 170:
            continue
        allowed_heights.append(height)
    assert allowed_heights == [175, 180, 172]

test_heights()

This test function checks that only heights of 170 cm or more are added to the allowed_heights list.

Thinking and Problem-Solving Tips

When approaching problems that involve the continue statement, consider the following strategies:

Conclusion

The continue statement is a powerful tool for controlling the flow of loops in Python. By understanding how to use it effectively, you can write more efficient and readable code. Remember to use continue judiciously and always ensure that your conditions are clear and well-documented.

Additional Resources

For further reading and practice, consider the following resources: