Course Content
Python Loops Tutorial
Python Loops Tutorial
Using Condition Statements in a while Loop
The if/else structure can be combined with a while
loop to add conditional logic for each iteration. This allows you to perform different actions based on specific conditions while the loop executes.
Example: Categorizing Cities by Name Length
Let's apply this concept to our travel_list
. The program will categorize cities as having "short" or "long" names depending on their length (less than 8 characters for short, 8 or more for long).
travel_list = ["Monako", "Luxemburg", "Liverpool", "Barcelona", "Munchen"] # Initialize index i = 0 # Categorize cities by name length while i < len(travel_list): if len(travel_list[i]) < 8: print(travel_list[i], "has a short name.") else: print(travel_list[i], "has a long name.") i += 1
Explanation:
- The index
i
is initialized to 0 to start from the first city; - The
while
loop runs as long asi
is less than the length of thetravel_list
; - Conditional Logic:
if
: checks if the length of the current city name is less than 8 characters and prints a message accordingly;else
: handles all other cases where the name length is 8 or more characters;
- The
i
variable is incremented at the end of each iteration to move to the next city.
Swipe to show code editor
Write a program using a while
loop and conditional statements to:
- Count the number of cities in the
travel_list
with names shorter than 8 characters. - Print the total count at the end.
Thanks for your feedback!
Using Condition Statements in a while Loop
The if/else structure can be combined with a while
loop to add conditional logic for each iteration. This allows you to perform different actions based on specific conditions while the loop executes.
Example: Categorizing Cities by Name Length
Let's apply this concept to our travel_list
. The program will categorize cities as having "short" or "long" names depending on their length (less than 8 characters for short, 8 or more for long).
travel_list = ["Monako", "Luxemburg", "Liverpool", "Barcelona", "Munchen"] # Initialize index i = 0 # Categorize cities by name length while i < len(travel_list): if len(travel_list[i]) < 8: print(travel_list[i], "has a short name.") else: print(travel_list[i], "has a long name.") i += 1
Explanation:
- The index
i
is initialized to 0 to start from the first city; - The
while
loop runs as long asi
is less than the length of thetravel_list
; - Conditional Logic:
if
: checks if the length of the current city name is less than 8 characters and prints a message accordingly;else
: handles all other cases where the name length is 8 or more characters;
- The
i
variable is incremented at the end of each iteration to move to the next city.
Swipe to show code editor
Write a program using a while
loop and conditional statements to:
- Count the number of cities in the
travel_list
with names shorter than 8 characters. - Print the total count at the end.
Thanks for your feedback!