Else Statements with Loops in Python

In Python, else statements can be used with loops to execute a block of code once the loop completes normally, meaning no break statement was encountered. This unique feature adds flexibility, allowing different outcomes based on whether the loop was fully executed or exited early.

Key Points on Else with Loops:

Example of Else with a For Loop:

This example uses a for loop to search for a number in a list. The else statement executes if the number is not found.

Code Example

numbers = [1, 2, 3, 4, 5]
        search_for = 6
        for num in numbers:
            if num == search_for:
                print("Number found!")
                break
        else:
            print("Number not found!")

Output

Number not found!

Example of Else with a While Loop:

In this example, the while loop runs as long as a counter is less than a limit. The else statement runs when the condition becomes false naturally.

Code Example 2

count = 0
        while count < 3:
            print("Counting:", count)
            count += 1
        else:
            print("Counting completed")

Output

Counting: 0
Counting: 1
Counting: 2
Counting completed

Detailed Explanation:

The else statement in Python loops is useful for distinguishing between loops that complete naturally and those that exit early, enabling more refined control flow.