×

python · level 3 · unit 2 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Functions can take names, defaults and any number of values.

Name an argument in a call, like order("tea", size="large"), and it becomes a : Python matches it by name, not position. Give a parameter a in the def line, size="medium", and callers can leave it out.

Put in the brackets to catch any number of extra values. They arrive as a tuple. Put to catch any extra keyword arguments. They arrive as a dictionary.

The stars work backwards in a call too: total(*prices) spreads a list out into separate arguments, and **options spreads a dictionary into keyword arguments.

def order(drink, *extras, size="medium", **notes):
    print(f"{size} {drink}")
    print("extras:", extras)
    print("notes:", notes)

order("latte", "oat milk", "vanilla", size="large", name="Sam")

The names args and kwargs are only a habit, because the stars do the real work.