Circular Journeys with While Loops
Deep Dive Into "while" Loops
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.
What Should You Expect?
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:
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, fewer countries would fit into the plan.
Here is what you'll get if you run this code:
Understanding Python's Built-In Functions
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. Callingcountry_costs.popitem()removes the last inserted entry from the dictionary and returns it as a(country, cost)tuple. That is why we writecountry, cost = country_costs.popitem(): the returned tuple is unpacked into two variables, so the key lands incountryand the value lands incost. Since every call removes an entry,country_costsshrinks with each iteration, and thewhileloop ends once the dictionary becomes empty. -
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.
