Python gives functions unusually flexible inputs — arguments by position or by name, optional parameters with defaults, and ways to accept any number of extra arguments. Mastering these makes your functions both easy to call and easy to extend.
Positional & keyword arguments
You can pass arguments by position (order matters) or by name (order doesn't). Keyword arguments make a call self-documenting:
def book(flight, seat, meal):...book("AI202", "12A", "veg") # positional — order mattersbook(flight="AI202", meal="veg", seat="12A") # keyword — clear & reorderable
Default values
Give a parameter a default to make it optional. Parameters with defaults must come after those without:
def greet(name, greeting="Hello"):return f"{greeting}, {name}!"greet("Aanya") # "Hello, Aanya!"greet("Aanya", "Welcome") # "Welcome, Aanya!"
*args and **kwargs
Accept any number of extra arguments: *args collects extra positionals into a tuple, **kwargs collects extra keywords into a dict:
def order(item, qty=1, *extras, **options):print(item, qty, extras, options)order("coffee") # coffee 1 () {}order("coffee", 2, "hot", "oat", size="large")# coffee 2 ('hot', 'oat') {'size': 'large'}# Unpack a list/dict INTO a call with * and **nums = [1, 2, 3]print(*nums) # same as print(1, 2, 3)
The mutable-default trap
Key takeaways
- 01Arguments can be passed by position or by keyword; keyword args are self-documenting.
- 02Defaults make parameters optional and must follow non-default parameters.
- 03*args collects extra positionals (tuple); **kwargs collects extra keywords (dict).
- 04* and ** also unpack a list/dict into a call.
- 05Never use a mutable default — it is shared across calls; use None instead.
