Python > Core Python Basics > Control Flow > Loop Control Statements (break, continue, pass)

Advanced Loop Control: Combining `break`, `continue`, and `else`

This snippet demonstrates a more complex use case involving `break`, `continue`, and the `else` clause in conjunction with a loop.

The `else` Clause in Loops

Python loops can have an else clause that executes if the loop completes without encountering a break statement. This is useful for determining if a specific condition was ever met within the loop.

Code Example with `break`, `continue`, and `else`

This code iterates through a list of numbers. Even numbers are skipped using continue. The inner loop checks if each odd number is prime. If a number is found to be not prime, the break statement is executed within the inner loop. The else clause is associated with the outer for loop and prints a message only if the outer loop completes without being interrupted by a break.

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

for number in numbers:
    if number % 2 == 0:
        continue  # Skip even numbers
    
    is_prime = True
    for i in range(2, int(number**0.5) + 1):
        if number % i == 0:
            is_prime = False
            break  # Number is not prime
    
    if is_prime:
        print(f'{number} is prime')
else:
    print('All odd numbers processed.')

Explanation of the Code

The outer loop iterates through the numbers list. If a number is even, it's skipped using continue. For odd numbers, the code checks if they're prime using an inner loop. If an odd number is found to be divisible by any number from 2 to its square root, it's not prime, and the inner loop breaks using break. If the outer loop completes without any break (meaning all numbers were processed), the else clause is executed, printing 'All odd numbers processed.'.

When to use `else` with loops

Use the else clause with loops when you need to execute code only if the loop completes normally (without encountering a break statement). It's particularly useful for scenarios where you're searching for something within a sequence and need to know if the search was successful or not.

Best Practices

Use the else statement with loops judiciously. Overuse can make code harder to read. Aim for clarity and readability. Consider alternatives when appropriate.

Real-Life Use Case

Imagine searching a database for a specific user. You iterate through the results. If the user is found, you process their data and break. If the loop completes without finding the user, the else block can handle the 'user not found' scenario.

FAQ

  • What happens if a `break` statement is encountered before the `else` clause?

    If a break statement is executed within the loop, the else clause is skipped entirely.
  • Can the `else` clause be used with `while` loops as well?

    Yes, the else clause works with both for and while loops in the same way.