1.2.28Introduction to Programming (Python)

Default parameters, keyword arguments

1,742 words8 min readdifficulty · medium1 backlinks

1. The vocabulary (WHAT)

def greet(name, greeting="Hello"):   # greeting has a default
    return greeting + ", " + name
 
greet("Asha")                # 'Hello, Asha'   -> default used
greet("Asha", "Namaste")     # 'Namaste, Asha' -> positional override
greet("Asha", greeting="Hi") # 'Hi, Asha'      -> keyword override

2. WHY defaults exist (derive the need)

Suppose you write a "connect to database" function. Almost always the port is 5432. Without defaults you'd write:

connect("localhost", 5432, "utf8", 30)   # everyone repeats the same junk

Every caller copies the same 5432, "utf8", 30. Repetition = bugs when one copy changes. So we bake the common value into the definition:

def connect(host, port=5432, encoding="utf8", timeout=30):
    ...
connect("localhost")                 # the easy, common case
connect("localhost", timeout=60)     # change ONLY what's unusual

3. WHY keyword arguments exist (HOW they help)

With many parameters, position is fragile. Reading box(2, 5, 0, 1) — which is width? height? Nobody knows. Keyword arguments make calls self-documenting and order-independent:

def box(width, height, x=0, y=0):
    ...
box(width=2, height=5)      # crystal clear
box(height=5, width=2)      # order doesn't matter with keywords
box(2, 5, y=1)              # mix: positional then keyword
Figure — Default parameters, keyword arguments

4. The ordering RULES (and WHY)

WHY Rule 1: Python fills parameters left-to-right by position. If a default came first, a positional argument given to it would be ambiguous — does it fill the default one or skip it? Forbidding it removes the ambiguity.

WHY Rule 2: Once you say d=9, Python no longer knows which slot a later bare 2 belongs to. Positionals must all be resolved first.


5. The famous mutable-default trap


6. Worked examples


Recall Feynman: explain to a 12-year-old

Imagine ordering pizza. The shop already assumes medium size and cheese unless you say otherwise — those are defaults. You only mention size if you want large. And instead of shouting toppings in a fixed secret order, you just say "topping = mushroom, size = large" — that's keyword arguments, naming what you want so nobody gets confused. One catch: never give the cook ONE shared topping bowl for everybody, or the next customer gets your leftovers — that's the mutable-default bug!


7. Active recall

What is the difference between a parameter and an argument?
Parameter = the name in the definition; argument = the actual value passed in the call.
What is a default parameter?
A parameter with a fallback value in the def (def f(x=10)); used if the caller omits it.
In a function definition, where must default parameters go?
After all non-default parameters (defaults drift right).
In a function call, can a keyword argument come before a positional one?
No — all positional args must come before any keyword args.
When is a default value evaluated — at definition or each call?
Once, at definition time (which causes the mutable-default trap).
Why is def f(x, lst=[]) dangerous?
The same list is shared across all calls because the default is created once at def time.
How do you fix the mutable-default trap?
Use None as default, then create a fresh object inside: if lst is None: lst = [].
What error do you get from greet("Asha", name="Asha")?
TypeError: got multiple values for argument 'name'.
Why use keyword arguments with many parameters?
They are self-documenting and order-independent, avoiding fragile positional mistakes.
How can you set the 3rd parameter while keeping the 2nd at its default?
Pass the 3rd by keyword, e.g. f(a, third=9).

Connections

Concept Map

value passed becomes

is a

provides

matches

matched by

matched by

motivates

motivates

enables

enables

constrains

constrains

Parameter in definition

Argument in call

Default parameter

Fallback value if omitted

Keyword argument

By name

Positional argument

By order

Repetition of common values

Fragile position order

Convenient common case

Self-documenting calls

Rule 1: non-defaults before defaults

Rule 2: positional before keyword

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Socho ek function ek machine hai jisme kuch knobs hote hain. Kuch knobs aapko har baar set karne padte hain (required parameters), lekin kuch knobs already ek default value pe set hote hain — yahi hai default parameter, jaise def greet(name, greeting="Hello"). Agar aap greeting nahi doge, to "Hello" automatically use ho jaayega. Isse common case ka code chhota aur clean rehta hai — yahi 80/20 ka funda hai.

Keyword arguments ka matlab hai value ko uske naam se dena, jaise greet("Asha", greeting="Hi"). Iska fayda — aapko parameters ka order yaad nahi rakhna padta, aur code padhne wale ko clear ho jaata hai ki kaunsi value kahan ja rahi hai. Do rules yaad rakho: definition me default parameters hamesha right side pe (non-default ke baad), aur call me positional arguments hamesha keyword arguments se pehle aate hain.

Ek bahut famous trap hai: kabhi bhi mutable default mat do, jaise def f(x, lst=[]). Kyunki ye list sirf ek baar banti hai jab def line chalti hai, sab calls usi list ko share karte hain — purana data leak ho jaata hai. Iska fix: default None rakho, aur function ke andar if lst is None: lst = [] likho — har call pe fresh list milegi. Bas yeh teen cheezein pakad lo aur defaults/keywords solid ho jaayenge.

Go deeper — visual, from zero

Test yourself — Introduction to Programming (Python)

Connections