Course Content
Python Loops Tutorial
Python Loops Tutorial
Nested for Loop
We will use a nested loop to print each city multiple times in a structured format, resembling a triangle pattern.
travel_list = ["Monako", "Luxemburg", "Liverpool", "Barcelona", "Munchen"] # Outer loop for controlling rows for i in range(1, len(travel_list) + 1): # Inner loop for controlling columns for j in range(i): print(travel_list[j], end=' ') # Print cities in a row print('') # Move to the next line after each row
- Outer loop:
the
for
loop withrange(1, len(travel_list) + 1)
determines the number of rows. Each iteration represents a row.i
controls how many cities are printed in the current row; - Inner loop:
the
for
loop withrange(i)
iterates over the cities to be printed in the current row.j
accesses the city names in thetravel_list
up to the current row index; - Printing:
the
print(travel_list[j], end=' ')
ensures cities are printed on the same row.print('')
moves to the next line after each row.
Swipe to start coding
You are working on a navigation system that processes lists of trips, where each trip includes multiple countries. However, a data processing error has caused all country names to appear in lowercase, making them unreadable by the system.
To fix this issue, you need to extract and format the country names correctly.
- Extract all country names from
trips
and store them incountries
. - Capitalize each country name before adding it to
countries
usingcapitalize()
method.
Solution
Thanks for your feedback!
Nested for Loop
We will use a nested loop to print each city multiple times in a structured format, resembling a triangle pattern.
travel_list = ["Monako", "Luxemburg", "Liverpool", "Barcelona", "Munchen"] # Outer loop for controlling rows for i in range(1, len(travel_list) + 1): # Inner loop for controlling columns for j in range(i): print(travel_list[j], end=' ') # Print cities in a row print('') # Move to the next line after each row
- Outer loop:
the
for
loop withrange(1, len(travel_list) + 1)
determines the number of rows. Each iteration represents a row.i
controls how many cities are printed in the current row; - Inner loop:
the
for
loop withrange(i)
iterates over the cities to be printed in the current row.j
accesses the city names in thetravel_list
up to the current row index; - Printing:
the
print(travel_list[j], end=' ')
ensures cities are printed on the same row.print('')
moves to the next line after each row.
Swipe to start coding
You are working on a navigation system that processes lists of trips, where each trip includes multiple countries. However, a data processing error has caused all country names to appear in lowercase, making them unreadable by the system.
To fix this issue, you need to extract and format the country names correctly.
- Extract all country names from
trips
and store them incountries
. - Capitalize each country name before adding it to
countries
usingcapitalize()
method.
Solution
Thanks for your feedback!