Learning Sections show
For Loop with Else in Python
In Python, a `for` loop can have an `else` clause that executes when the loop completes normally (i.e., not interrupted by a `break` statement). Here are some examples:
1. Basic Example
In this example, the `else` block executes because the loop completes without encountering a `break` statement.
# A list of numbers
numbers = [1, 2, 3, 4, 5]
# Iterate through the list
for number in numbers:
print(number)
else:
print("Loop completed without break")
# Output:
# 1
# 2
# 3
# 4
# 5
# Loop completed without break
2. With Break
In this example, the `else` block does not execute because the loop is terminated by a `break` statement.
# A list of numbers
numbers = [1, 2, 3, 4, 5]
# Iterate through the list
for number in numbers:
if number == 3:
break
print(number)
else:
print("Loop completed without break")
# Output:
# 1
# 2
3. Searching in a List
Using `else` with a `for` loop can be helpful for search operations where you need to know if an item was found or not.
# A list of fruits
fruits = ['apple', 'banana', 'cherry']
# Item to search for
search_item = 'banana'
# Iterate through the list
for fruit in fruits:
if fruit == search_item:
print(fruit, "found!")
break
else:
print(search_item, "not found!")
# Output:
# banana found!
4. No Break
When the item is not found, the `else` block executes because the loop completes normally.
# A list of fruits
fruits = ['apple', 'banana', 'cherry']
# Item to search for
search_item = 'orange'
# Iterate through the list
for fruit in fruits:
if fruit == search_item:
print(fruit, "found!")
break
else:
print(search_item, "not found!")
# Output:
# orange not found!