Skip to contentSkip to navigation

Module 05 · Lesson 02

Positional & Keyword Arguments

Make functions flexible: pass arguments by position or by name, give parameters default values, avoid the shared default list trap, and accept any number of arguments with *args and **kwargs.

  • About 8 minutes
  • Builds on earlier lessons
  • 12-question quiz at the end

What you will learn

  • Position or name
  • Default values
  • Any number of values
  • Watch defaults fill gaps

Ways to hand values in

You can pass values by position, by name, rely on defaults, or accept any number of them.

  • Positional

    describe("cat", 3) fills the parameters in order.

  • Keyword

    describe(age=3, pet="cat") names each one, so the order does not matter.

  • Defaults

    def tea(sugar=0): means sugar is 0 unless the caller says otherwise.

  • Any number

    *args collects extra values into a tuple; **kwargs collects extra names into a dictionary.

You already use these

Built-in functions lean on keyword arguments and defaults all the time.

  • print()sep= and end= are keyword arguments with defaults: a space and a new line.
  • sorted()sorted(scores, reverse=True) flips the order with one named setting.
  • Game settingsstart_game(level=1, sound=True) works with no arguments and lets players change one.
  • max() and min()They take any number of values, just like a function with *args.

A parameter with a default

This first line has a required parameter and an optional one. Tap each part to see its job.

Part 1 of 4

Tap any part of the code below, or press Next.1 of 4 explored

required:No default, so every call must give a value: greet("Ana").

Pass values every way

Pick an example, change it, then press Run. Say what you expect to see before you press.

Example 1 of 6By name

Keyword arguments can come in any order.

Your turn: Call it once more with the values swapped by position. What goes wrong?

Python
def describe(pet, age):
    print(f"A {age} year old {pet}")

describe("cat", 3)
describe(age=5, pet="dog")
Output
Press Run to see what it prints.

Watch defaults fill the gaps

Press Step to run one line at a time. Watch which values come from the call and which from the defaults.

Ready. Press Step to run the first line.

  1. def ticket(film, seats=1, snack="none"):
  2. return f"{film} x{seats}, snack: {snack}"
  3. first = ticket("Space Cats")
  4. second = ticket("Robots", 3, snack="popcorn")
  5. print(first)
  6. print(second)

Output so far

Nothing printed yet.

What Python does

Python reads the program from the top. Nothing has run yet.

Names

None yet.

Quick guesses

Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.

Question 1 of 6

1.Using a default: what prints?

def f(a, b=2):
    return a * b

print(f(5))

0 of 6 answered

Common argument misconceptions

Each card is something beginners often believe. Tap it to see what Python really does.

Misconception 1 of 4

Notes

Everything above, in words. Open it when you want the full explanation.

Read the notesOpen

Flexible ways to pass values

Positional and keyword arguments

So far every call has used positional arguments: values matched to parameters by their order. You can also pass keyword arguments, which name the parameter they are for. Keyword arguments can come in any order.

Try it 1: edit me, then Run
def introduce(name, age):
    print(f"{name} is {age}")

introduce("Mina", 12)            # positional
introduce(age=12, name="Mina")   # keyword: order does not matter
introduce("Mina", age=12)        # mixed
Output
Press Run to see what it prints.

All three calls print Mina is 12. When you mix the two kinds, positional arguments must come first. introduce(name="Mina", 12) is a SyntaxError, and giving the same parameter twice, as in introduce("Mina", name="Kai"), is a TypeError.

Keyword arguments are most useful for values whose meaning is not obvious at the call site, such as numbers and True or False. Compare resize(img, 300, 200, True) with resize(img, width=300, height=200, keep_ratio=True).

Default values

A parameter can have a default value, written with = in the definition. If the caller leaves that argument out, the default is used.

Try it 2: edit me, then Run
def greet(name, greeting="Hello", punctuation="!"):
    print(f"{greeting}, {name}{punctuation}")

greet("Kai")                         # Hello, Kai!
greet("Kai", "Hi")                   # Hi, Kai!
greet("Kai", punctuation="?")        # Hello, Kai?
Output
Press Run to see what it prints.

Parameters with defaults must come after those without, so def greet(greeting="Hello", name): is a SyntaxError. You have used defaults many times already: print() has sep=" " and end="\n", and sorted() has reverse=False.

The shared default trap

A default value is created once, when the function is defined, not each time it is called. For numbers and strings that never matters. For a list or dictionary it matters a lot, because every call that uses the default shares the same object.

Try it 3: edit me, then Run
def add_item(item, basket=[]):
    basket.append(item)
    return basket

print(add_item("tea"))      # ['tea']
print(add_item("milk"))     # ['tea', 'milk'], surprise!
Output
Press Run to see what it prints.

The fix is the standard Python pattern: use None as the default and create a new list inside the function.

Try it 4: edit me, then Run
def add_item(item, basket=None):
    if basket is None:
        basket = []
    basket.append(item)
    return basket
Output
Press Run to see what it prints.

Now each call that leaves out basket gets a fresh empty list. Never use [], {} or set() as a default.

Any number of positional arguments: *args

Some functions should accept as many values as the caller likes, as print() does. A parameter written with a star, conventionally *args, collects every extra positional argument into a tuple.

Try it 5: edit me, then Run
def total(*numbers):
    result = 0
    for n in numbers:
        result += n
    return result

print(total(2, 3))           # 5
print(total(1, 2, 3, 4))     # 10
print(total())               # 0
Output
Press Run to see what it prints.

Normal parameters can come before it: in def show(title, *items):, the first argument goes to title and the rest are collected in items.

Any number of keyword arguments: **kwargs

Two stars, conventionally **kwargs, collect every extra keyword argument into a dictionary, with the parameter names as keys.

Try it 6: edit me, then Run
def profile(name, **details):
    print(name)
    for key, value in details.items():
        print(f"  {key}: {value}")

profile("Ana", age=14, town="Leeds")
Output
Press Run to see what it prints.

This prints the name and then age: 14 and town: Leeds. The full order of parameters in a definition is: normal parameters, *args, parameters with defaults that can only be given by keyword, then **kwargs.

Keyword-only parameters

Parameters listed after *args, or after a bare *, can only be passed by keyword. This forces callers to name options, which protects them from mixing up the order.

Try it 7: edit me, then Run
def book(room, *, nights=1, breakfast=False):
    return f"{room}: {nights} nights, breakfast {breakfast}"

print(book("Blue", nights=3, breakfast=True))
Output
Press Run to see what it prints.

book("Blue", 3, True) would raise TypeError, which is exactly the point: the call has to say what 3 and True mean.

Unpacking into a call

The stars also work the other way, in a call. *list spreads a list into positional arguments, and **dict spreads a dictionary into keyword arguments.

Try it 8: edit me, then Run
numbers = [4, 5, 6]
print(total(*numbers))                       # same as total(4, 5, 6)
options = {"greeting": "Hey", "punctuation": "."}
greet("Bo", **options)                       # Hey, Bo.
Output
Press Run to see what it prints.

Reading a signature

The first line of a definition, with its parameters, is called the function's signature, and learning to read one is a skill in itself. Take sorted(iterable, *, key=None, reverse=False) from the documentation: one required positional argument, then a bare star, so key and reverse can only be passed by name, and both have defaults. print(*objects, sep=" ", end="\n") says print takes any number of values and two keyword options. Once you can read signatures, the documentation for any function tells you at a glance how to call it, and help(name) in the editor shows the same line.

Choosing parameters well

When you design your own function, put the values every caller must supply first, as plain positional parameters, in the order a reader would expect: move(piece, row, column), not move(column, piece, row). Give sensible defaults to options that most callers will not change. Make true or false flags keyword-only, so every call says what the flag means. And keep the list short; four or five parameters is a lot, and a long list is often a sign that the function should be split.

Together, defaults, keywords and stars let you design calls that are short for the common case and clear for the rare one. Use them for readability, not cleverness: a function with a dozen options is usually doing too many jobs.

Syntax

The general shape of the statements in this lesson.

syntax.py
f(1, 2)          f(a=1, b=2)        f(1, b=2)        # positional first
def f(a, b=10):                                       # default
def f(a, items=None): items = [] if items is None else items
def f(*args):        # args is a tuple
def f(**kwargs):     # kwargs is a dictionary
def f(a, *, flag=False):                              # keyword-only after *
f(*my_list)      f(**my_dict)                         # unpack into a call
Output
Press Run to see what it prints.

Worked examples

Read the problem, run the code, then read why it works.

Example 1 of 2

A flexible receipt line

Beginner

Write a function that formats a receipt line with a default currency and width, then call it in several ways.

Python
def line(item, price, currency="GBP", width=12):
    return f"{item:<{width}}{price:>7.2f} {currency}"

print(line("Tea", 2.5))
print(line("Croissant", 3.2, width=14))
print(line(price=9.99, item="Lunch", currency="EUR"))
Output
Press Run to see what it prints.

Predict first

How it works(open after your guess)

The first call relies on both defaults. The second changes only the width, by name, so the currency default still applies. The third passes everything by keyword in a different order. A width can even be given inside the f-string format with nested braces, {width}.

Common pitfalls

Mistakes people make with this topic, and what to write instead.

Pitfall 1 of 3

A list as a default value

Spot the bug

Can you see what is wrong? Run it to watch it go wrong, then open the fix.

Buggy code: run it
def log(msg, history=[]):
    history.append(msg)
    return history

log("a")
print(log("b"))
Output
Press Run to see what it prints.
Show what goes wrong and the fix

What happens

Prints ['a', 'b'] instead of ['b']

Write this instead

def log(msg, history=None):
    if history is None:
        history = []
    history.append(msg)
    return history

log("a")
print(log("b"))

Why it happens

The default list is created once and shared by every call that does not pass its own list.

In the real world

Where this shows up in software people use every day.

  1. Building a pizza order

    Food delivery

    A delivery app builds an order summary from a size, any number of toppings and optional extras given by name.

    Why Python fits

    *toppings takes any number of toppings, delivery is keyword-only with a default, and **extras accepts options the function does not need to know about in advance.

    Python
    def order(size, *toppings, delivery=True, **extras):
        parts = [f"{size} pizza"]
        if toppings:
            parts.append("with " + ", ".join(toppings))
        for name, value in extras.items():
            parts.append(f"{name}={value}")
        parts.append("delivered" if delivery else "collect")
        return " | ".join(parts)
    
    print(order("Large", "ham", "olives", drinks=2))
    print(order("Small", delivery=False))
    Output
    Press Run to see what it prints.

Key takeaways

Tick each one you could explain to a friend.

0 of 5

Common questions

Guess the answer first, then open it.

Do I have to call them args and kwargs?

No, only the stars matter. Descriptive names such as *scores or **options are often clearer.

When should I use keyword-only parameters?

For options, especially True or False flags, where a bare value in a call would be unclear.

Is a default evaluated every call?

No, once when the def runs. That is why mutable defaults are shared and why None is the safe choice.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Where to go next

The quiz and the Lab live on their own pages, so this lesson stays about learning.

Finished this lesson?

Create an ID or sign in to save your progress across devices.

Create ID to save
Lessons done in this module0/3 complete
Quiz

Check what you learned

12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.

Lab

Keep going in the Lab

7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.

Review

Spaced review

Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.

This lesson at a glance

The 7 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.

What else you can search for and explore

Curious to go further? Each card opens a web search in a new tab.

References

Look things up here whenever you need the exact details.