🐸

The Keyword Vault

Python Basicspython-architect-04-kwargs
Reward: 120 XP
|

Complex Customization

The Archmage asks Hoppy to build a new type of Magic Golem.

These Golems are complex, and customer requests vary wildly: Some want material="Iron", others want weapon="Sword", some want height=5, and some even want name="Bob".

If we listed every possible parameter on the blueprint, the list would be a mile long!

The Keyword Vault (**kwargs)

Add two stars ** before a parameter name, and it becomes a vault that can hold any amount of Labeled Data (technically called a Dictionary).

def build_golem(**options):
  print("Order Config:")
  for key, value in options.items():
      print(key + ": " + str(value))

Now you can call it with any label=value pairs:

  • build_golem(material="Wood", type="Guard")
  • build_golem(name="Bob", power=9000, color="Red")

Your Mission

1
Define Blueprint

Create a function named configure_robot that takes **specs.

2
Read Labels

Inside, print("Robot Specs:"), then loop through specs.items() to print all configuration items.

3
Build Robot

Call the function with these specs: type="Battle", cpu="M1", armor="Titanium".

Order Rules

In a function definition:

  1. Regular args (x)
  2. Default args (y=1)
  3. *args (The Box)
  4. **kwargs (The Vault) kwargs must ALWAYS be last!
Suggested Solution
Expand
Solution:
def configure_robot(**specs):
  print("Robot Specs:")
  for part, model in specs.items():
      print(part + ": " + model)

configure_robot(type="Battle", cpu="M1", armor="Titanium")
Advanced Tips
Want more? Click to expand

F. Bridge to Reality

  • Keyword Vault = Keyword Arguments, often named kwargs.
  • Double Star ()** = Dictionary Unpacking.
  • This is one of Python's superpowers. Many complex libraries (like plotting with Matplotlib or querying databases in Django) rely heavily on **kwargs to let users pass optional configurations without changing the function signature.
Loading...
Terminal
Terminal
Ready to run...