Functions at Depth: Default and Keyword Arguments
Giving a parameter a default so callers can leave it out, and naming arguments at the call so their order stops mattering. This is how one function serves several jobs without a second copy of the code.
What a learner can do afterwards
- Write a function with a default parameter and call it with and without that argument
- Call a function with named arguments given out of order and predict the result
- Say why a default that is a shared collection can surprise the caller
1 · Read
Arguments passed by place are called positional. They land in the parameters in order, so greeting("Hiya", "Ash", 2) puts "Hiya" in msg, "Ash" in name and 2 in count. Arguments that name their parameter are called keyword. With names, order stops mattering, so greeting(count=2, name="Ash", msg="Hiya") prints Hiya Ash twice. When you mix the two, every positional value must come first.
A default is a fallback value written in the definition, as in def greeting(msg, name="Friend", count=1). Calling greeting("Hi") prints Hi Friend once, using both defaults. Calling greeting("Hi", "Ash", 3) replaces them and prints Hi Ash three times. You must still pass every parameter that has no default, so greeting() with no arguments fails.
Never use a list as a default value. Python builds the default only once, so every call shares the same list. Items appended in one call are still there on the next call, which surprises the caller.
Defaults let one function serve several jobs without a second copy of the code. Common calls stay short while rare tweaks pass their own values, and the signature documents the normal choice. Style point: write greet(name="Ash") with no spaces around the equals sign.
Name arguments to escape order, give defaults for the usual values, and never default to a shared list.
2 · Watch
Take it off screen
Where it sits
This opens up
Nothing builds on it yet.
8 questions wait behind this lesson, each with its answer explained. Every answer feeds the sky: stars light as they are learned, and dim when it is time to come back.