Break and Continue in Python

Break and Continue in Python: Controlling Loop Execution

Break and Continue in Python: Controlling Loop Execution

Loops in Python allow us to execute a block of code repeatedly. However, sometimes we need to **control** the loop's behavior—either by **stopping** it early or **skipping** certain iterations. This is where `break` and `continue` statements come in.

Why Use `break` and `continue`?

  • Efficient Loop Control: Stop loops when necessary.
  • Skip Unwanted Iterations: Avoid unnecessary execution.
  • Optimized Performance: Reduce iterations in large data sets.

The `break` Statement

The `break` statement **stops** a loop immediately when a condition is met.

# Using break in a loop
for num in range(1, 10):
    if num == 5:
        break  # Stops the loop when num is 5
    print(num)

# Output:
# 1
# 2
# 3
# 4

As soon as `num == 5`, the loop **terminates** completely, skipping any further iterations.

The `continue` Statement

The `continue` statement **skips** the current iteration and moves to the next one.

# Using continue in a loop
for num in range(1, 10):
    if num == 5:
        continue  # Skips printing 5, moves to next iteration
    print(num)

# Output:
# 1
# 2
# 3
# 4
# 6
# 7
# 8
# 9

When `num == 5`, the `continue` statement **skips** the `print(num)` line but **does not stop** the loop.

Using `break` and `continue` in `while` Loops

These statements also work inside `while` loops:

# Using break in a while loop
count = 1
while count < 10:
    if count == 5:
        break  # Exit loop when count is 5
    print(count)
    count += 1
# Using continue in a while loop
count = 0
while count < 10:
    count += 1
    if count == 5:
        continue  # Skip iteration when count is 5
    print(count)

Conclusion

Using `break` and `continue` allows for **fine control** over loops, making programs more efficient and flexible. Where do you think these statements will be useful in your projects?


Comments

Popular posts from this blog

Match Statement in Python

For loop and while loop in python