If/Else у Вкладеному Циклі
The if/else
statements are essential for adding conditions to nested loops. They allow you to filter, process, or categorize data, such as identifying specific values in lists or matrices.
Let's adapt this concept to a practical task: filtering travel expenses. If an expense exceeds a certain budget threshold, we'll mark it as "Expensive"
; otherwise, print the original expense.
Suppose you have a list of trips, and each trip contains expenses for categories like flights, hotels, food, and activities. Your goal is to check each expense:
If the expense exceeds $200 , mark it as
Expensive
;Otherwise, print the original expense.
# Travel expenses for multiple trips travel_costs = [ [500, 150, 100, 50], # Trip 1 [200, 300, 120, 80], # Trip 2 [180, 220, 130, 170] # Trip 3 ] # Setting outer while loop to work with rows (trips) i = 0 while i < len(travel_costs): j = 0 print(f"Trip {i + 1} expenses: ", end='') # Label for the current trip # Setting inner while loop to work with expenses in the current trip while j < len(travel_costs[i]): if travel_costs[i][j] > 200: # Check if expense is greater than 200 print('Expensive', end=' ') else: print(travel_costs[i][j], end=' ') j += 1 # Move to the next expense print('') # Move to the next line after each trip i += 1 # Move to the next trip
Зовнішній цикл while ітерується через кожну подорож у списку
travel_costs
, використовуючи індексi
;Внутрішній цикл while проходить через витрати для поточної подорожі, використовуючи індекс
j
;Умова
if/else
перевіряє, чи витрата перевищує $200 ;Після обробки всіх витрат для подорожі програма переходить на наступний рядок і продовжує до наступної подорожі.
Swipe to start coding
Вам надано список витрат на подорожі для кількох поїздок. Кожна поїздка представлена як вкладений список, що містить різні витрати, такі як транспорт, проживання, їжа та активності. Ваше завдання - обробити ці витрати, визначивши "дешеві" витрати, зберігаючи ту ж вкладену структуру.
- Вам надано двовимірний список (список списків), де кожен внутрішній список представляє витрати однієї поїздки.
- Ітеруйте через список витрат кожної поїздки.
- Замініть будь-які витрати в розмірі $100 або менше на
"Cheap"
, залишаючи інші значення незмінними. - Збережіть трансформовані витрати в новому двовимірному списку з тією ж структурою
Рішення
Дякуємо за ваш відгук!