In Python, the for-else loop offers a unique construct that combines the traditional for-loop with an optional else block. This else block executes only under specific conditions, providing a clean way to handle scenarios after the loop completes normally.
Structure:
For-else loop structure
for item in iterable:
# Loop body (statements executed for each item in the iterable)
if condition: # Optional condition
# Optional statements to execute if the condition is met
else:
# Statements executed only if the loop completes normally
# (i.e., without encountering a `break` statement)
Key Points:
⯌
Iteration: The for loop iterates through the elements of an iterable (like a list, string, or tuple).
⯌
Loop Body: For each iteration, the statements within the loop body are executed using the current item from the iterable.
⯌
Optional Condition: You can include an optional if condition within the loop body. If this condition evaluates to True for any iteration, the loop exits, and any statements following it (including the else block) are skipped.
⯌
else Block Execution: The else block executes only if the loop completes iterating through all elements in the iterable and no break statement was used to terminate the loop prematurely. This allows you to perform actions specific to the successful completion of the loop.
Basic example
For else loop basic example in python
numbers = [1, 2, 3, 4, 5]
found_even = False
for num in numbers:
if num % 2 == 0: # Check for even number
found_even = True
break # Exit the loop if even number is found
else:
print("No even number found in the list.")
if found_even:
print("An even number was found in the list.")
Output
An even number was found in the list.
Explanation :
⯌ The loop iterates through the numbers list.
⯌ If an even number is encountered (num % 2 == 0), found_even is set to True, and the loop is terminated using break.
⯌ Since the loop exits due to break, the else block is skipped.
⯌ The outer if statement checks if found_even was changed, indicating an even number was found.
Use Cases:
⯌ Checking Conditions After Loop Completion: The else block is ideal for performing actions that depend on whether the loop iterated through all elements successfully. For example, checking if a specific value was found in a list.
⯌ Cleaning Up Resources: If the loop involves resource management (like opening files), the else block can be used to ensure proper cleanup, even if the loop terminates early due to a condition.
Remember:
⯌ The else block won't execute if the loop exits using break.
⯌ Use for-else judiciously to avoid overly complex loop structures. Consider using a flag or separate loop for specific post-processing if needed.
⯌ By effectively using the for-else loop, you can enhance the readability and efficiency of your Python code for various looping tasks.
Examples of for-else loop
Checking if a number is prime:
Checking if a number is prime or not using for-else in python
num = 17
for i in range(2, num):
if num % i == 0:
print(f"{num} is not a prime number")
break
else:
print(f"{num} is a prime number")
Output
17 is a prime number
Searching for an item in a list:
Searching for an item in a list using for-else loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
if fruit == "mango":
print("Mango is in the list")
break
else:
print("Mango is not in the list")
Output
Mango is not in the list
Checking if a string contains a vowel:
Checking if a string contains a vowel in python
word = "rhythm"
for char in word:
if char in "aeiou":
print("The word contains a vowel")
break
else:
print("The word does not contain a vowel")
Output
The word does not contain a vowel
Checking if all numbers in a list are positive:
Checking if numbers in a list are positive in python
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num <= 0:
print("Not all numbers are positive")
break
else:
print("All numbers are positive")
Output
All numbers are positive
Checking if a number is in a range:
Checking if a number is in a range using for-else loop
num = 10
for i in range(5, 15):
if num == i:
print(f"{num} is in the range")
break
else:
print(f"{num} is not in the range")
Output
10 is in the range
Checking if a list contains a duplicate:
Checking if a list contains a duplicate in python
numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers)):
for j in range(i + 1, len(numbers)):
if numbers[i] == numbers[j]:
print("The list contains a duplicate")
break
else:
continue
break
else:
print("The list does not contain a duplicate")
Output
The list does not contain a duplicate
Checking if a string is a palindrome:
Checking if a string is a palindrome or not in python
word = "radar"
for i in range(len(word) // 2):
if word[i] != word[-i - 1]:
print("The word is not a palindrome")
break
else:
print("The word is a palindrome")
Output
The word is a palindrome
Checking if a number is a Fibonacci number:
Checking if a number is a Fibonacci number or not in python
num = 13
a, b = 0, 1
while a < num:
if a == num:
print(f"{num} is a Fibonacci number")
break
a, b = b, a + b
else:
print(f"{num} is not a Fibonacci number")
Output
13 is not a Fibonacci number
Checking if a number is a perfect square:
Checking if a number is a perfect square using for-else loop in python
num = 16
for i in range(1, num + 1):
if i * i == num:
print(f"{num} is a perfect square")
break
else:
print(f"{num} is not a perfect square")
Output
16 is a perfect square
Checking if a number is a perfect cube:
Cube or not example using for-else loop in python
num = 27
for i in range(1, num + 1):
if i * i * i == num:
print(f"{num} is a perfect cube")
break
else:
print(f"{num} is not a perfect cube")
Output
27 is a perfect cube
In each of these examples, the for loop goes through each item in the iterable (list, string, dictionary, set, or tuple) and executes the code block for each item. If the for loop completes normally (without encountering a break), the else block is executed.