🐸

The Flexible Box

Python Basicspython-architect-03-flex
Reward: 120 XP
|

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.

1
Connect Warehouse

import inventory at the top.

2
Flexible Mover

Define a function store_all using *loots as the parameter.

3
Batch Storage

Inside the function, write a for loop to go through loots. For every loot, call inventory.add(loot).

4
Test Run

Call store_all("Diamond", "Ruby", "Sapphire") to store three gems at once.

Star logic

Note: The star * is only needed when defining (def). When using the variable (in the for loop), don't use the star!

Suggested Solution
Expand
Solution:
import inventory

def store_all(*loots):
  for loot in loots:
      inventory.add(loot)

store_all("Diamond", "Ruby", "Sapphire")
Advanced Tips
Want more? Click to expand

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).
Loading...
Terminal
Terminal
Ready to run...