Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Nested while Loop | Nested Loops
Python Loops Tutorial
course content

Course Content

Python Loops Tutorial

Python Loops Tutorial

1. The for Loop
2. The while Loop
3. Nested Loops

book
Nested while Loop

In real life, you may need to organize or analyze data with multiple levels, such as tracking expenses for different trips. A nested while loop allows you to process these multi-dimensional scenarios efficiently when the number of iterations isn't predetermined.

Example: Organizing Travel Expenses

Imagine you have multiple trips, and each trip has a list of expenses (flights, hotels, food, etc.). Using a nested while loop, you can calculate the total cost for each trip.

123456789101112131415161718192021
# List of trips with their respective expenses travel_costs = [ [500, 200, 100, 150], # Trip 1: Flights, Hotels, Food, Activities [600, 250, 120, 200], # Trip 2: Flights, Hotels, Food, Activities [550, 180, 130, 170] # Trip 3: Flights, Hotels, Food, Activities ] # Initialize the outer loop to iterate over trips i = 0 while i < len(travel_costs): total_cost = 0 # Reset the total cost for the current trip j = 0 # Inner loop to iterate over expenses in each trip while j < len(travel_costs[i]): total_cost += travel_costs[i][j] # Add the expense to the total cost j += 1 # Print the total cost for the current trip print(f"Total cost for Trip {i + 1}: ${total_cost}") i += 1 # Move to the next trip
copy

Explanation

  1. Outer Loop (while i < len(travel_costs)): iterates through the list of trips, where each row represents the expenses for a single trip;
  2. Inner Loop (while j < len(travel_costs[i])): iterates through the expenses for the current trip, summing them up in the total_cost variable;
  3. Print Results: after summing up expenses for a trip, the program prints the total cost for that trip;
  4. Move to the Next Trip: increment i to analyze the next trip until all trips are processed;
  5. Final Output: after the loop completes, print the trip number with the highest total cost and its value.

Note

Nested loops are commonly used to iterate through n-dimensional matrices, where each level of nesting represents a dimension. In our tasks, we are working with a 2-dimensional matrix, such as a list of trips and their expenses. Nested loops are also helpful for dynamic looping scenarios, like input validation or navigating multi-level menus, where the number of iterations isn’t fixed and depends on changing conditions or user input.

Task
test

Swipe to show code editor

Increment every element in the matrix by 1.

Write a program using nested while loops to:

  1. Calculate the total cost for each trip.
  2. Find and print the trip number with the highest total cost.

Expected Output:

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 2
toggle bottom row

book
Nested while Loop

In real life, you may need to organize or analyze data with multiple levels, such as tracking expenses for different trips. A nested while loop allows you to process these multi-dimensional scenarios efficiently when the number of iterations isn't predetermined.

Example: Organizing Travel Expenses

Imagine you have multiple trips, and each trip has a list of expenses (flights, hotels, food, etc.). Using a nested while loop, you can calculate the total cost for each trip.

123456789101112131415161718192021
# List of trips with their respective expenses travel_costs = [ [500, 200, 100, 150], # Trip 1: Flights, Hotels, Food, Activities [600, 250, 120, 200], # Trip 2: Flights, Hotels, Food, Activities [550, 180, 130, 170] # Trip 3: Flights, Hotels, Food, Activities ] # Initialize the outer loop to iterate over trips i = 0 while i < len(travel_costs): total_cost = 0 # Reset the total cost for the current trip j = 0 # Inner loop to iterate over expenses in each trip while j < len(travel_costs[i]): total_cost += travel_costs[i][j] # Add the expense to the total cost j += 1 # Print the total cost for the current trip print(f"Total cost for Trip {i + 1}: ${total_cost}") i += 1 # Move to the next trip
copy

Explanation

  1. Outer Loop (while i < len(travel_costs)): iterates through the list of trips, where each row represents the expenses for a single trip;
  2. Inner Loop (while j < len(travel_costs[i])): iterates through the expenses for the current trip, summing them up in the total_cost variable;
  3. Print Results: after summing up expenses for a trip, the program prints the total cost for that trip;
  4. Move to the Next Trip: increment i to analyze the next trip until all trips are processed;
  5. Final Output: after the loop completes, print the trip number with the highest total cost and its value.

Note

Nested loops are commonly used to iterate through n-dimensional matrices, where each level of nesting represents a dimension. In our tasks, we are working with a 2-dimensional matrix, such as a list of trips and their expenses. Nested loops are also helpful for dynamic looping scenarios, like input validation or navigating multi-level menus, where the number of iterations isn’t fixed and depends on changing conditions or user input.

Task
test

Swipe to show code editor

Increment every element in the matrix by 1.

Write a program using nested while loops to:

  1. Calculate the total cost for each trip.
  2. Find and print the trip number with the highest total cost.

Expected Output:

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 2
Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
We're sorry to hear that something went wrong. What happened?
some-alt