Python Tutorials

Mastering Loops in Python: break and continue Statements

Spread the love

Loops are fundamental to programming, allowing us to execute blocks of code repeatedly. However, sometimes we need finer control over the iteration process. Python’s break and continue statements provide this control, allowing us to exit loops prematurely or skip iterations, respectively.

Table of Contents

The break Statement

The break statement immediately terminates the loop it’s contained within. Execution resumes at the first statement after the loop’s block. This is particularly useful when a condition is met that necessitates immediate loop termination.

Example (for loop):


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for num in numbers:
    if num == 5:
        break  # Exit the loop when num is 5
    print(num)

print("Loop finished")

This code prints numbers 1 through 4, then exits the loop when num becomes 5. The output is:

1
2
3
4
Loop finished

Example (while loop):


count = 0
while True:
    print(count)
    count += 1
    if count > 5:
        break  # Exit the loop when count exceeds 5

This prints 0 through 5, then the loop terminates.

The continue Statement

The continue statement skips the rest of the current iteration and proceeds directly to the next iteration of the loop. The loop itself does not terminate.

Example (for loop):


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for num in numbers:
    if num % 2 == 0:  # Check if the number is even
        continue  # Skip even numbers
    print(num) #Only print odd numbers

print("Loop finished")

This prints only odd numbers because even numbers cause the continue statement to skip the print statement. The output is:

1
3
5
7
9
Loop finished

Example (while loop):


count = 0
while count < 10:
    count += 1
    if count == 5:
        continue  # Skip when count is 5
    print(count)

This prints numbers 1 through 10, except for 5.

Comparing break and continue

Both break and continue modify loop behavior, but in different ways. break completely exits the loop, while continue skips only the current iteration. The choice depends on whether you need to terminate the loop entirely or just process the next iteration.

Leave a Reply

Your email address will not be published. Required fields are marked *