Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn break/continue in a Nested Loop | Nested Loops
Python Loops Tutorial
Sectionย 3. Chapterย 4
single

single

bookbreak/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
copy
  • Outer loop: iterates through the list of trips using the index i;
  • Inner loop: processes each expense in the current trip;
  • break in the inner loop: if an expense exceeds the budget, the break statement stops processing expenses for the current trip.
Task

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:

  1. Iterate through the expenses in order.

  2. Ignore any expense strictly less than $100.

  3. Find the first expense strictly greater than $200.

  4. As soon as such an expense is found:

    • Add it to the significant_expenses list.
    • Stop checking the remaining expenses for that trip using break.
  5. 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

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

Sectionย 3. Chapterย 4
single

single

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt