Welcome back! I hope you're prepared for another exciting lesson. Our journey through loops in Python continues. You've already built a strong foundation with for
loops. Now, we'll enrich that knowledge with while
loops.
Think of while
loops as a trusty friend who continues performing a task as long as a condition holds true. It keeps going until the condition fails or a break
command halts it. Let's illustrate how it functions with a code snippet related to planning a trip based on the budget for the countries you want to visit:
Python1# We have a budget for the trip and each country costs a certain amount 2travel_budget = 5000 3country_costs = {"France": 1000, "Italy": 800, "Spain": 900, "Japan": 1200} 4 5total_cost = 0 6chosen_countries = [] 7 8# Let's add countries to our trip until our budget runs out using a while loop 9while total_cost < travel_budget and country_costs: 10 country, cost = country_costs.popitem() 11 if total_cost + cost <= travel_budget: 12 total_cost += cost 13 chosen_countries.append(country) 14 15print("Countries chosen for the trip:", chosen_countries)
We commence with a while
loop that verifies two conditions — whether our total_cost
is less than our travel_budget
, and whether there are still countries left in the country_costs
dictionary. The loop keeps running, popping items from the dictionary, and adding them to our trip until one of the conditions fails.
In this specific case, our budget is enough to go to all countries so the loop stops when country_costs
is empty and there are no more countries to consider. If you were to adjust the travel_budget
to a lower number the loop should stop sooner when the first condition is no longer met (i.e. total_cost < travel_budget
).
Here is what you'll get if you run this code:
Plain text1Countries chosen for the trip: ['Japan', 'Spain', 'Italy', 'France']
As we dive into Python's built-in functions, it's like discovering a set of powerful tools that make coding simpler. Python comes packed with these ready-to-use functions, saving you the time and effort of writing common functionalities from scratch. For beginners, focusing on a few key functions can be incredibly helpful.
In our example of planning a trip with a while
loop, we specifically use two functions: popitem()
and append()
. You might also come across functions like len()
, which tells you how many items are in a list or dictionary, and print()
, which shows your results on the screen.
popitem()
: This function is specific to dictionaries. It removes the last added item and returns it, which is helpful for our loop as it allows us to take countries off our planning list one by one.
append()
: Used with lists, this lets you add new items to the end. For us, it means we can keep adding countries to our travel list until we hit our budget limit.
Both popitem()
and append()
are simple yet powerful, allowing us to dynamically update our lists and dictionaries.
Understanding while
loops solidifies your ability to automate repetitive tasks and control your iterations fluidly. This understanding opens new avenues for coding efficiency and simplicity. Once mastered, this tool provides incredible flexibility and helps you navigate complex tasks with ease.
Isn't that exciting? We're now prepared to start the practice section. You can roll up your sleeves and dive into the world of while
loops, enhancing your Python skills one iteration at a time!