Python For Each Loop

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 standard for loop syntax. It iterates over each element in the iterable (e.g., a list, tuple, string, etc.) and assigns each element to the variable.
  • # 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, the break statement is executed, which terminates the loop prematurely.
  • else:: This is the else block associated with the for loop. It is executed if the for loop completes without any break 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.