The for else loop in Python is a unique feature that adds flexibility to control flow. It allows you to distinguish between loops that complete naturally and those interrupted by a break. By understanding and utilizing this construct, you can write more expressive and intentional Python code.
Understanding the For Else Loop
The for else loop in Python allows you to execute a block of code when the for loop completes its iteration normally (i.e., without encountering a break statement). The syntax is as follows:
for item in sequence:
# Code block for iteration
else:
# Code block to execute if the loop didn't encounter a break
The else block is executed only if the for loop finishes iterating over the sequence without being interrupted by a break statement.
How for else Works
Here’s a basic example to illustrate the for-else loop:
In this example, the loop iterates over all elements in the numbers
list and then execute the else
block because no break
the statement was encountered.
Python
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
else:
print("Loop completed without encountering a break.")
Output
1
2
3
4
5
Loop completed without encountering a break.
Practical Use Cases of for else
The for-else construct can be particularly useful in scenarios where you need to determine if a loop was exited prematurely (using break) or if it completed all iterations.
Use Case 1: Searching for an Element
One common use case is searching for an element in a sequence. If the element is found, you can break out of the loop; otherwise, the else block can handle the case where the element is not found.
Python
numbers = [10, 20, 30, 40, 50]
target = 35
for num in numbers:
if num == target:
print(f"Found {target}")
break
else:
print(f"{target} not found in the list.")
Output
35 not found in the list.
Use Case 2: Checking for Prime Numbers
Another practical application is checking for prime numbers. You can use the for-else loop to verify if a number has any divisors other than 1 and itself.
In this example, the loop checks for factors of number
and breaks if any are found. If no factors are found, the else
block confirms that the number is prime.
Python
number = 29
for i in range(2, number):
if number % i == 0:
print(f"{number} is not a prime number.")
break
else:
print(f"{number} is a prime number.")
Output
29 is a prime number.