Python break and continue Statements


In Python, loops (like for and while) are essential constructs for repeating a block of code. But sometimes, you might want to control the flow of the loop more precisely. That’s where the break and continue statements come in. They allow you to alter the normal behavior of a loop and provide more flexibility in your code.

In this blog post, we will explore what the break and continue statements are, how to use them, and provide examples that demonstrate their use cases.


What is the break Statement?

The break statement is used to exit from a loop (either for or while) prematurely, stopping further iterations. Once break is encountered, the loop terminates, and the program continues with the next statement after the loop.

Basic Syntax of break:

for item in sequence:
    if condition:
        break
    # Code to execute

The break statement is most commonly used when a specific condition is met, and you want to stop the loop early.

Example 1: Using break in a for Loop

# Example: Using break in a for loop
for i in range(10):
    if i == 5:
        print("Breaking the loop at i =", i)
        break
    print(i)

Output:

0
1
2
3
4
Breaking the loop at i = 5

In this example:

  • The loop starts from i = 0 and iterates through the range.
  • When i equals 5, the break statement is executed, and the loop terminates immediately, printing the message and stopping further iterations.

What is the continue Statement?

The continue statement is used to skip the current iteration of the loop and proceed with the next iteration. Unlike break, which exits the loop entirely, continue only skips the current iteration and the loop continues to the next one.

Basic Syntax of continue:

for item in sequence:
    if condition:
        continue
    # Code to execute

The continue statement is typically used when you want to skip certain values or conditions but continue processing the rest of the sequence.

Example 2: Using continue in a for Loop

# Example: Using continue in a for loop
for i in range(5):
    if i == 3:
        print("Skipping i =", i)
        continue
    print(i)

Output:

0
1
2
Skipping i = 3
4

In this example:

  • When i equals 3, the continue statement is executed, which skips printing the value 3 but continues with the next iteration (i.e., 4).
  • The loop prints all values except 3.

Using break and continue in while Loops

Both break and continue can also be used in while loops to control the flow of iteration, just like in for loops. The syntax remains the same.

Example 3: Using break in a while Loop

# Example: Using break in a while loop
count = 0

while count < 5:
    if count == 3:
        print("Breaking the loop at count =", count)
        break
    print(count)
    count += 1

Output:

0
1
2
Breaking the loop at count = 3

In this example:

  • The while loop iterates as long as count is less than 5.
  • When count equals 3, the break statement stops the loop.

Example 4: Using continue in a while Loop

# Example: Using continue in a while loop
count = 0

while count < 5:
    count += 1
    if count == 3:
        print("Skipping count =", count)
        continue
    print(count)

Output:

1
2
Skipping count = 3
4
5

In this case:

  • The loop increments count on each iteration.
  • When count is 3, the continue statement is executed, skipping the print statement for count = 3 and moving on to the next iteration (count = 4).

Using break and continue Together

It is possible to use both break and continue in the same loop. For example, you may want to continue with the next iteration when a certain condition is met, but also break out of the loop if another condition is satisfied.

Example 5: Using Both break and continue in the Same Loop

# Example: Using both break and continue in the same loop
for i in range(10):
    if i == 2:
        print("Skipping i =", i)
        continue
    if i == 8:
        print("Breaking the loop at i =", i)
        break
    print(i)

Output:

0
1
Skipping i = 2
3
4
5
6
7
Breaking the loop at i = 8

In this example:

  • When i == 2, the continue statement skips that iteration.
  • When i == 8, the break statement is executed, stopping the loop entirely.

Practical Example: Search for a Value in a List

Let's combine both break and continue to search for a specific value in a list.

# Example: Searching for a value in a list
items = ['apple', 'banana', 'cherry', 'date', 'elderberry']
search_term = 'cherry'

for item in items:
    if item == 'banana':  # Skip bananas
        continue
    if item == search_term:
        print(f"Found {search_term}!")
        break
    print(f"Checked {item}")

Output:

Checked apple
Checked banana
Found cherry!

In this example:

  • The loop skips checking banana using the continue statement.
  • When it finds the search_term (in this case, "cherry"), it prints a message and exits the loop using break.

When to Use break and continue?

  • Use break: When you want to exit the loop entirely based on a specific condition.
    • For example, breaking out of a loop when a certain item is found in a list, or when a user enters an invalid input.
  • Use continue: When you want to skip the current iteration of the loop and continue with the next iteration.
    • For example, skipping over certain elements in a list (e.g., skip processing invalid data).