For Else
Introduction:
- In Python, the For Else construct combines a For loop with an else block. The else block specifies code that should be executed when the For loop completes normally, without encountering a break statement.
- The For Else construct is useful for running code that should execute if the loop iterates through all its elements without interruption.
Syntax of For Else:
python
for element in iterable:
# Loop body
# ...
else:
# Code to run if the loop completes without a break statement
# ...
- The else block does not execute if the For loop encounters a break statement.
Examples:
- A Simple For Else Example:
Iterating over a list of strings using a For loop with an else block.
pythonlist_1 = ['apple', 'banana', 'cherry'] for item in list_1: print(item) else: print('\nPrinted all the items in iterable.')Output:
apple banana cherry Printed all the items in iterable.
- For Else with Break Statement:
Checking if a list of strings contains a string with a length of 3.
pythonlist_1 = ['apple', 'cherry', 'mango'] for item in list_1: if len(item) == 3: print('Item with length 3 is found.') break else: print('Item with length 3 is NOT found.')Output:
Item with length 3 is NOT found.
Exercises:
- Simple For Else Loop:
Create a list of fruits and use a for else loop to print each fruit. If the loop completes normally, print a message.
pythonfruits = ['apple', 'banana', 'cherry'] for fruit in fruits: print(fruit) else: print('Printed all the fruits.')
- For Else with Break:
Create a list of numbers and use a for else loop to check if the list contains the number 5. If found, print a message and break the loop. If not, print a different message.
pythonnumbers = [1, 2, 3, 4, 6, 7] for number in numbers: if number == 5: print('Number 5 found.') break else: print('Number 5 not found.')
Summary:
- In this tutorial, we learned about the For Else construct in Python, its syntax, execution flow, and how to use it in programs. Practice using For Else to perform actions after looping through all elements in an iterable, without introducing additional flags or variables!