Control Flow for Loops: Break and Continue

Using break and continue in Python Loops

After understanding the basics of loops in Python, it’s time to explore two important control statements: break and continue. These statements give us greater control over how our loops execute, allowing us to either exit a loop prematurely or skip certain iterations. Think of these like emergency brakes or track switches in our railway yard analogy.

Understanding the break Statement

The break statement is used to exit a loop before it has completed all iterations. It's like an emergency brake for the loop—it stops the loop immediately when a certain condition is met. This can be useful when searching for something and you want to stop the loop as soon as you find it.

Example: Breaking Out of a Loop

# Example: Stop the loop when number 7 is found
for i in range(1, 11):
    if i == 7:
        print("Number 7 found! Stopping the loop.")
        break
    print(f"Current number: {i}")

Output:

Current number: 1
Current number: 2
Current number: 3
Current number: 4
Current number: 5
Current number: 6
Number 7 found! Stopping the loop.

Explanation: In this example, the loop prints numbers from 1 to 10. However, when it reaches number 7, the break statement is executed, and the loop is terminated immediately.

🚨

Caution: Using break will completely exit the loop. If you want to only skip specific iterations, consider using continue instead.

Understanding the continue Statement

The continue statement is used to skip the current iteration of a loop and move to the next one. It’s like a track switch that bypasses the current station and moves on to the next. This is useful when you need to skip over certain values that do not meet specific criteria.

Example: Skipping Even Numbers

# Example: Print only odd numbers from 1 to 10
for i in range(1, 11):
    if i % 2 == 0:
        continue
    print(f"Current number: {i}")

Output:

Current number: 1
Current number: 3
Current number: 5
Current number: 7
Current number: 9

Explanation: In this example, the loop checks if the current number is even using i % 2 == 0. If it is, the continue statement is executed, and the loop moves on to the next iteration without printing the current number.

💡

Tip: Use continue when you need to skip certain conditions while still allowing the rest of the loop to execute.

Using break and continue in while Loops

Just like with for loops, the break and continue statements can be used effectively in while loops to control the flow.

Example: Exiting a while Loop

# Example: Break the loop when a condition is met
i = 1
while i <= 10:
    if i == 5:
        print("Reached 5, breaking out of the loop.")
        break
    print(f"Current value of i: {i}")
    i += 1

Output:

Current value of i: 1
Current value of i: 2
Current value of i: 3
Current value of i: 4
Reached 5, breaking out of the loop.

Example: Skipping Iterations in a while Loop

# Example: Skip printing value 5 in the loop
i = 1
while i <= 10:
    if i == 5:
        i += 1
        continue
    print(f"Current value of i: {i}")
    i += 1

Output:

Current value of i: 1
Current value of i: 2
Current value of i: 3
Current value of i: 4
Current value of i: 6
Current value of i: 7
Current value of i: 8
Current value of i: 9
Current value of i: 10

Key Takeaways

  • break is used to exit a loop entirely when a specific condition is met, similar to an emergency brake on a train.
  • continue is used to skip the current iteration of the loop and proceed to the next one, just like bypassing a particular track in a railway yard.
  • Both break and continue can be used with for loops and while loops to give finer control over loop execution.

Exercise: Practice with break and continue

Exercise 1: Finding Prime Numbers

# Find prime numbers between 1 and 20, stop if a non-prime number is found (simulated condition)
for num in range(2, 21):
    for i in range(2, num):
        if num % i == 0:
            break
    else:
        print(f"Prime number: {num}")

Exercise 2: Skipping Multiples of 3

# Print numbers from 1 to 15, but skip multiples of 3
for i in range(1, 16):
    if i % 3 == 0:
        continue
    print(f"Number: {i}")

🚂

Looking Ahead: Now that you understand how to control the flow of loops using break and continue, you are ready to learn about nested loops and how they can be used to solve more complex problems, similar to managing multiple tracks in a complex railway network.