Course Content
Python Loops Tutorial
Python Loops Tutorial
The else Statement in a while Loop
In Python, the else
block can be added to a while
loop. The else
block executes when the loop terminates normally, meaning the loop condition becomes False
without encountering a break
statement.
The else
block runs when the loop condition becomes False
, signifying the loop has completed all iterations.
travel_list = ['Monako', 'Luxemburg', 'Liverpool', 'Barcelona', 'Munchen'] # Initialize index i = 0 # Iterate through the destinations while i < len(travel_list): print(travel_list[i]) i += 1 else: print('All destinations have been listed!')
In this example, the while
loop iterates through each destination in the travel_list
and prints it. Once all destinations are listed, the condition i < len(travel_list)
becomes False
, triggering the else
block, which confirms completion.
If the loop terminates with a break
statement (e.g., when a specific city is found), the else
block does not execute.
# List of travel destinations travel_list = ['Monako', 'Luxemburg', 'Liverpool', 'Barcelona', 'Munchen'] # Initialize index i = 0 # Search for a specific destination while i < len(travel_list): if travel_list[i] == 'Barcelona': break print(travel_list[i]) i += 1 else: # This won't execute if break is triggered. print('All destinations have been listed!')
Here, the loop stops as soon as it finds 'Barcelona'
. The else
block is skipped because the loop does not terminate normally but is interrupted by the break
statement.
Thanks for your feedback!