Unknown Loot
Returning from adventure, Hoppy needs to store loot in the warehouse. The problem: sometimes he finds 1 Gem, other times 3 Swords, or a pile of junk.
If we define save(item1), it fails with two items. If we define save(item1, item2), it fails with one item.
"I need a Flexible Box," Hoppy says. "One that expands to fit however many items I throw at it."
The Flexible Box (*args)
Add a star * before the parameter name, and it becomes a magical box (technically called a Tuple).
def save_loot(*items):
print("Received " + str(len(items)) + " items:")
for item in items:
print("- " + item)
Now you can call it however you like:
save_loot("Gold")(1 item)save_loot("Sword", "Shield", "Potion")(3 items)save_loot()(Empty works too!)
Your Mission
There is a warehouse system inventory.py ready for use.
import inventory at the top.
Define a function store_all using *loots as the parameter.
Inside the function, write a for loop to go through loots. For every loot, call inventory.add(loot).
Call store_all("Diamond", "Ruby", "Sapphire") to store three gems at once.
Note: The star * is only needed when defining (def). When using the variable (in the for loop), don't use the star!
Suggested SolutionExpandCollapse
import inventory
def store_all(*loots):
for loot in loots:
inventory.add(loot)
store_all("Diamond", "Ruby", "Sapphire")Advanced TipsWant more? Click to expandClick to collapse
F. Bridge to Reality
- Flexible Box = Variable Arguments, often named
args. - Star (*) = Unpacking Operator.
- This is crucial when you don't know how many arguments a user will pass (just like
print()can handle any number of inputs).