Part 05 / Topic 2 of 9
Parameters and arguments
Parameters are the names in the def line. Arguments are the values you pass in.
Real-world example: sending an order confirmation.
def confirm(name, item, qty=1): # qty has a default value
return f"{name} ordered {qty} x {item}"
print(confirm("Asha", "Dosa")) # Asha ordered 1 x Dosa
print(confirm("Asha", "Dosa", 3)) # positional
print(confirm(item="Idli", name="Ravi")) # keyword (order does not matter)
Output of the middle two lines:
Asha ordered 3 x Dosa
Ravi ordered 1 x Idli
Keyword-only parameters (*)
Everything after a bare * must be passed by name. This makes calls easy to read.
def book_ticket(city, *, seats, ac=False):
return f"{seats} seat(s) to {city}, AC={ac}"
print(book_ticket("Pune", seats=2, ac=True)) # 2 seat(s) to Pune, AC=True
# book_ticket("Pune", 2) -> TypeError: takes 1 positional argument but 2 were given
*args and **kwargs
*argscollects any number of positional arguments into a tuple.**kwargscollects any number of keyword arguments into a dict.
def add_all(*args):
print(args)
return sum(args)
print(add_all(10, 20, 30)) # prints (10, 20, 30), then 60
def make_profile(name, **kwargs):
print(name, kwargs)
make_profile("Meera", city="Chennai", age=21)
# Meera {'city': 'Chennai', 'age': 21}
Unpacking into a call
Use * to spread a list into positional arguments, and ** to spread a dict into keyword arguments.
def confirm(name, item, qty=1):
return f"{name} ordered {qty} x {item}"
order = ["Kiran", "Vada", 2]
print(confirm(*order)) # Kiran ordered 2 x Vada
details = {"name": "Neha", "item": "Poha"}
print(confirm(**details)) # Neha ordered 1 x Poha
| Kind | Example in def |
How you call it |
|---|---|---|
| Positional | def f(a, b) |
f(1, 2) |
| Keyword | def f(a, b) |
f(b=2, a=1) |
| Default | def f(a, b=5) |
f(1) or f(1, 9) |
| Keyword-only | def f(a, *, b) |
f(1, b=2) |
*args |
def f(*args) |
f(1, 2, 3) |
**kwargs |
def f(**kwargs) |
f(x=1, y=2) |
Order inside def: normal → default → *args → keyword-only → **kwargs.
🔍 Going deeper: the names
argsandkwargsare only a habit; the*and**do the work. There is also a positional-only marker/: indef f(a, /, b),acannot be passed by name. You will see it inhelp(len)→len(obj, /).
Done here? The practice set for Part 5 — 8 exercises with solutions — is on the part page.