In Python, a for-else
loop is a control structure that combines a for
loop with an else
block. It allows you to specify a block of code that should be executed if the for
loop completes its iteration without encountering a specific condition. The else
block will be executed when the for
loop runs to completion without any break
statements being executed within the loop.
Here's the syntax for a for-else
loop in Python:
for variable in iterable:
# Loop body
if condition:
break
else:
# Code to execute when the for loop completes without any break statement
Let's break down the components of a for-else
loop:
for variable in iterable:
: This is the standardfor
loop syntax. It iterates over each element in theiterable
(e.g., a list, tuple, string, etc.) and assigns each element to thevariable
.# Loop body
: This is where you place the code that should be executed on each iteration of the loop.if condition: break
: This line is used to check a specific condition during each iteration of the loop. If the condition is met, thebreak
statement is executed, which terminates the loop prematurely.else:
: This is theelse
block associated with thefor
loop. It is executed if thefor
loop completes without anybreak
statements being executed.
Now, let's look at an example to better understand how for-else
loops work:
fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']
for fruit in fruits:
if 'c' in fruit:
print(f'Found a fruit with the letter "c": {fruit}')
break
else:
print("No fruit with the letter 'c' found.")
In this example, we have a list of fruits, and we are using a for
loop to iterate through them. Inside the loop, we check if the current fruit
contains the letter 'c'. If it does, we print a message and then use the break
statement to exit the loop prematurely. If the break
statement is never executed, the loop completes its iteration.
The else
block is executed when the loop completes without any break
statements being executed. In this case, it means that no fruit with the letter 'c' was found, so the message "No fruit with the letter 'c' found." is printed.
So, the for-else
loop is a useful construct for handling situations where you want to perform some action if a condition is never met during the iteration of a loop.