Python for-else Loop

Introduction to Python for-else Loop

In Python, the for-else loop is a control flow structure that combines the for loop and the else statement. It allows you to iterate over a sequence of elements and execute a block of code if the loop completes normally, without encountering any break statements. The else block is executed only if the loop has exhausted all the items in the sequence.

Syntax of the for-else Loop

The syntax of the for-else loop in Python is as follows:


for item in sequence:
    # Code to be executed inside the loop
    if condition:
        break
else:
    # Code to be executed if the loop completes normally

The for loop iterates over each item in the sequence, and if a condition is met, the break statement is used to exit the loop prematurely. If the loop completes without encountering a break statement, the else block is executed.

Example 1: Finding Prime Numbers

Let’s say we want to find all the prime numbers between 1 and 10 using a for-else loop:


for num in range(1, 11):
    for i in range(2, num):
        if num % i == 0:
            break
    else:
        print(num, "is a prime number")

In this example, the outer loop iterates over the numbers from 1 to 10. The inner loop checks if the number is divisible by any number from 2 to the number itself. If a factor is found, the inner loop is terminated using the break statement. If no factor is found, the else block is executed, and the number is printed as a prime number.

Example 2: Searching for an Element

Let’s consider a scenario where we want to search for a specific element in a list using a for-else loop:


my_list = [1, 2, 3, 4, 5]
search_element = 6

for item in my_list:
    if item == search_element:
        print("Element found!")
        break
else:
    print("Element not found!")

In this example, the for loop iterates over each item in the list. If the search element is found, the loop is terminated using the break statement, and the message “Element found!” is printed. If the loop completes without finding the element, the else block is executed, and the message “Element not found!” is printed.

Benefits of Using for-else Loops

The for-else loop in Python provides a concise and readable way to handle scenarios where you want to execute a block of code only if the loop completes normally, without any premature termination. It can be particularly useful when searching for an element in a sequence or performing validation checks.

By utilizing the for-else loop, you can avoid using additional flags or variables to track the status of the loop and make your code more readable and maintainable.

Conclusion

The for-else loop in Python is a powerful control flow structure that allows you to iterate over a sequence and execute a block of code if the loop completes normally. It provides an elegant way to handle scenarios where you want to perform actions only when the loop has exhausted all the elements without encountering any break statements. By understanding and utilizing this construct, you can write more efficient and readable code in Python.

Scroll to Top