python · level 3 · unit 2 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Stars in the call this time. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
def greet(first, last, greeting="Hello"):
return f"{greeting}, {first} {last}!"
person = {"first": "Ada", "last": "Lovelace"}
print(greet(**person))
print(greet(*["Alan", "Turing"], greeting="Hi"))
your turn
Your turn. Call a logger with any number of parts.
Call log a second time with your own level, two values of your choice and your own sep, like " | ". Remember the quotes around text.
fix it
Python refuses to book the room. Fix the call!
- Python will not run this at all. Read the error: which kind of argument should come first?
- Arguments without names must come before keyword arguments in a call.
- Move "Sea View" to the front, so it says book("Sea View", nights=3), then run.
nailed it
your functions take whatever you give them. :D
- Keyword arguments match by name. Defaults make them optional.
*argsgathers extras in a tuple,**kwargsin a dictionary.- In a call,
*spreads a list and**spreads a dictionary.
new words in your collection
- keyword argument
- default value
- *args
- **kwargs
This lesson isn’t saved. A free account remembers every lesson you finish.