In Python, loops (for and while) can have an optional else block. This is a unique and advanced feature of Python that isn't commonly found in other programming languages.
The else block in a loop executes only if the loop completes its execution normally.
If the loop is terminated prematurely by a break statement, the else block will not be executed.
for item in iterable:
# Code to execute for each item
if condition:
break # This will skip the else block
else:
# Code to execute if the loop finishes without breakingwhile condition:
# Code to execute while condition is true
if break_condition:
break # This will skip the else block
else:
# Code to execute if the condition becomes false normallyWithout else (Standard approach):
numbers = [1, 3, 5, 7, 9]
target = 4
found = False
for num in numbers:
if num == target:
print(f"Found {target}!")
found = True
break
if not found:
print(f"{target} is not in the list.")Output:
4 is not in the list.
With else (Pythonic approach):
numbers = [1, 3, 5, 7, 9]
target = 4
for num in numbers:
if num == target:
print(f"Found {target}!")
break
else:
print(f"{target} is not in the list.")Output:
4 is not in the list.
Notice how the else block makes the code cleaner by eliminating the need for the found flag variable.
retries = 3
while retries > 0:
print(f"Attempting to connect... ({retries} retries left)")
# Simulating a connection failure
connection_successful = False
if connection_successful:
print("Connected successfully!")
break
retries -= 1
else:
print("Failed to connect after all attempts. Please try again later.")Output:
Attempting to connect... (3 retries left)
Attempting to connect... (2 retries left)
Attempting to connect... (1 retries left)
Failed to connect after all attempts. Please try again later.
In this example, since connection_successful is always False, the loop naturally exhausts retries to 0. Thus, the else block executes.
- The
elseblock executes when the loop condition evaluates toFalse(forwhile) or when the iterable is exhausted (forfor). - A
continuestatement does not bypass theelseblock. Theelseblock will still run when the loop finishes. - If the loop never runs (e.g., iterating over an empty list, or
while False:), theelseblock will execute immediately.