Intermediate 8 min

Positional and keyword arguments

Python binds each argument you pass to a parameter in the function definition.

How it works

Position fills parameters in order, and an explicit name fills the matching parameter. In the greeting example the first argument supplies name and the named argument sets message. Supplying a value for the same parameter twice is an error, even if the two values happen to match.

Walk through an example

In def greet(name, message="Hi"), passing greet("Mira") sets name to Mira and leaves message at its default. You can also specify message="Hello" by name.

What to watch for

A mutable default is created once at function definition. Use None and initialize a new collection inside if each call needs fresh state.

Code example

def greet(name, message="Hi"):
    return f"{message}, {name}!"

print(greet("Mira", message="Hello"))

Check your understanding

Which value binds to message?

See the example and explanation
Worked example
Given greet('Mira', message='Hello')
Answer Hello

The named argument directly selects the message parameter and overrides its default.

Open practice problem
Next lessonIterators and generators