Parameters and arguments
Overview
The functions in the last lesson took a fixed list of arguments in a fixed order. Real functions often need to be more flexible: options with sensible defaults, arguments named for clarity, or any number of values. Python’s parameter system handles all of it.
Positional and keyword arguments
def describe_pet(name, animal):
print(f"{name} is a {animal}.")
describe_pet("Rex", "dog") # positional: matched by order
describe_pet(animal="cat", name="Tom") # keyword: matched by name
describe_pet("Polly", animal="parrot") # mixed: positional firstKeyword arguments make calls self-explanatory, especially for numbers and booleans: compare resize(800, 600, True) with resize(width=800, height=600, keep_ratio=True).
The rule for mixing: positional arguments come first. describe_pet(name="Rex", "dog") is a SyntaxError.
Default values
Give a parameter a default and callers can leave it out:
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Asha") # Hello, Asha!
greet("Ben", "Welcome back") # Welcome back, Ben!
greet("Chen", greeting="Hi") # Hi, Chen!Parameters with defaults must come after those without: def greet(greeting="Hello", name): is a SyntaxError.
You’ve used defaults all along: print(..., sep=" ", end="\n"), round(x, ndigits=None), sorted(items, reverse=False).
The full picture
*args: any number of positional arguments
A parameter starting with * collects all extra positional arguments into a tuple:
def average(*numbers):
return sum(numbers) / len(numbers)
average(4, 8) # numbers = (4, 8) → 6.0
average(1, 2, 3, 4) # numbers = (1, 2, 3, 4) → 2.5The name args is a convention (*args); use a meaningful name like *numbers when you can.
Keyword-only parameters
Any parameter after *args (or after a bare *) can only be passed by keyword:
def connect(host, *, timeout=10, secure=True):
...
connect("example.com", timeout=5) # fine
connect("example.com", 5) # TypeError: takes 1 positional argument but 2 were givenThis forces callers to write timeout=5 rather than a mysterious 5 — great for options and flags.
**kwargs: any number of keyword arguments
A parameter starting with ** collects extra keyword arguments into a dictionary:
def make_profile(name, **details):
print(name, details)
make_profile("Asha", city="Pune", role="Engineer")
# Asha {'city': 'Pune', 'role': 'Engineer'}The required order in a definition is: normal parameters, defaults, *args, keyword-only, **kwargs.
Unpacking arguments in a call
* and ** also work the other way, spreading a list or dict into a call:
point = (3, 4)
rectangle_area(*point) # same as rectangle_area(3, 4)
options = {"sep": " | ", "end": "!\n"}
print("a", "b", **options) # a | b!The mutable default trap
This is one of Python’s most famous gotchas:
def add_item(item, basket=[]):
basket.append(item)
return basket
print(add_item("apple")) # ['apple']
print(add_item("pear")) # ['apple', 'pear'] ← what?!A default value is created once, when the def runs — not each time the function is called. So every call without a basket shares the same list, which keeps growing.
The fix is a standard idiom — use None as the default and create a fresh list inside:
def add_item(item, basket=None):
if basket is None:
basket = []
basket.append(item)
return basketDefaults that can’t be changed — numbers, strings, None, True/False, tuples — are perfectly safe.
Arguments and mutation
When you pass a list to a function, the function gets a name for the same list (just like b = a in Lists). Changes inside the function are visible outside:
def add_bonus(scores):
for i in range(len(scores)):
scores[i] += 5
marks = [70, 80]
add_bonus(marks)
print(marks) # [75, 85]Sometimes that’s what you want, but it’s often surprising. Usually it’s clearer to return a new list and leave the input untouched: return [s + 5 for s in scores].
Guidelines: required parameters first, then options with defaults; make flags keyword-only; and never use
[]or{}as a default.
A coffee order function
Write order(drink, size="M", *extras, takeaway=False, **notes) that returns a one-line summary. Rules: size is shown in brackets; extras are joined with +; takeaway adds (takeaway); each note is added as [key: value]. Then call it four ways so that it prints exactly the four lines in the comment, including one call that uses only keyword arguments in a different order. Finally, fix add_item so that two separate calls don’t share the same list.
def order(drink, size="M", *extras, takeaway=False, **notes):
...
# Expected:
# Latte (M)
# Latte (L) + oat milk + vanilla
# Tea (S) (takeaway) [name: Asha]
# Mocha (M) (takeaway)
# Fix this function:
def add_item(item, basket=[]):
basket.append(item)
return basket
print(add_item("apple")) # should be ['apple']
print(add_item("pear")) # should be ['pear'], not ['apple', 'pear']def order(drink, size="M", *extras, takeaway=False, **notes):
text = f"{drink} ({size})"
for extra in extras:
text += f" + {extra}"
if takeaway:
text += " (takeaway)"
for key, value in notes.items():
text += f" [{key}: {value}]"
return text
print(order("Latte"))
print(order("Latte", "L", "oat milk", "vanilla"))
print(order("Tea", "S", takeaway=True, name="Asha"))
print(order(takeaway=True, drink="Mocha"))
# Fixed: use None as the default and create a new list inside
def add_item(item, basket=None):
if basket is None:
basket = []
basket.append(item)
return basket
print(add_item("apple")) # ['apple']
print(add_item("pear")) # ['pear']Summary
- Positional arguments fill parameters in order; keyword arguments (
size="L") fill them by name, in any order. - Default values (
size="M") make parameters optional; they must come after required ones. *argscollects extra positional arguments into a tuple;**kwargscollects extra keyword arguments into a dict.- Parameters after
*(or*args) are keyword-only, which makes calls liketakeaway=Trueexplicit. - Never use a mutable default like
[]— it’s shared between calls; useNoneand create the list inside.