single
break/continue in a Nested Loop
Swipe to show menu
Let's apply the concepts of break and continue to analyze travel costs practically. We'll combine a while loop and a for loop to process expenses across multiple trips.
Imagine you have multiple trips, and each trip has a list of expenses. If any expense exceeds a specific budget threshold, we will stop processing that trip immediately.
12345678910111213141516171819202122232425# List of trips with their respective expenses travel_costs = [ [100, 150, 300, 50], # Trip 1 [200, 500, 100, 80], # Trip 2 [120, 180, 400, 150] # Trip 3 ] # Budget threshold budget = 200 # Outer while loop to iterate through trips i = 0 while i < len(travel_costs): print(f"Processing expenses for Trip {i + 1}:") # Inner for loop to iterate through expenses for cost in travel_costs[i]: # If expense exceeds the budget if cost > budget: print('Expense', cost, 'exceeds the budget. Stopping this trip.') break print('Expense:', cost) i += 1 # Move to the next trip print('') # Add a new line for readability
- Outer loop: iterates through the list of trips using the index
i; - Inner loop: processes each expense in the current trip;
breakin the inner loop: if an expense exceeds thebudget, thebreakstatement stops processing expenses for the current trip.
Swipe to start coding
You are analyzing travel expenses from multiple trips. Each trip contains a list of expenses in the following order: transportation, accommodation, food, and activities.
Your goal is to extract one value per trip using strict filtering rules.
For each trip:
-
Iterate through the expenses in order.
-
Ignore any expense strictly less than $100.
-
Find the first expense strictly greater than $200.
-
As soon as such an expense is found:
- Add it to the
significant_expenseslist. - Stop checking the remaining expenses for that trip using
break.
- Add it to the
-
If a trip contains no expense greater than $200, do not add anything for that trip.
At the end, print the list of first significant expenses.
Solution
Thanks for your feedback!
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat