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.
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!")
Example: Breaking the Loop
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: print("All destinations have been listed!") # This won't execute if break is triggered.
Swipe to show code editor
Imagine planning your travel within a fixed budget. This program dynamically calculates and prints the cost of each trip as long as your budget allows. Once the budget is exhausted, the else
statement provides a closing message confirming that all affordable trips have been planned.
This program demonstrates how to use the else
block with a while
loop effectively.
Expected Output:
Thanks for your feedback!
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.
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!")
Example: Breaking the Loop
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: print("All destinations have been listed!") # This won't execute if break is triggered.
Swipe to show code editor
Imagine planning your travel within a fixed budget. This program dynamically calculates and prints the cost of each trip as long as your budget allows. Once the budget is exhausted, the else
statement provides a closing message confirming that all affordable trips have been planned.
This program demonstrates how to use the else
block with a while
loop effectively.
Expected Output:
Thanks for your feedback!