Parameters and arguments

Topic 2 of 5 in Functions6 min readBeginnerFree course

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

Python
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 first

Keyword 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:

Python
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

Kinds of parameters in def order(item, size=“M”, *extras, gift=False, **notes): item is a required positional; size=“M” has a default value; *extras collects extra positionals into a tuple; gift=False is keyword-only because it comes after the star; **notes collects extra keywords into a dict. order(“tea”) gives item=“tea”, size=“M”. order(“tea”, “L”, “lemon”, “honey”) gives extras=(“lemon”, “honey”). order(“tea”, gift=True, note=“Happy birthday”) gives notes={“note”: “Happy birthday”}. order(size=“S”, item=“cake”) uses keyword arguments in any order.

*args: any number of positional arguments

A parameter starting with * collects all extra positional arguments into a tuple:

Python
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.5

The 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:

Python
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 given

This 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:

Python
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:

Python
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:

Python
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:

Python
def add_item(item, basket=None):
    if basket is None:
        basket = []
    basket.append(item)
    return basket

Defaults 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:

Python
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.

Exercise

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.

Python
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']

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.
  • *args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict.
  • Parameters after * (or *args) are keyword-only, which makes calls like takeaway=True explicit.
  • Never use a mutable default like [] — it’s shared between calls; use None and create the list inside.