Python Functions
Python Function Arguments
Python gives you several flexible ways to pass arguments into a function — by position, by name, with a default value, or as an arbitrary, variable-length set. Knowing all four makes your functions much more usable.
Positional Arguments
Positional arguments are matched to parameters purely by their order. The first value you pass fills the first parameter, the second value fills the second parameter, and so on — so the order you write them in really matters.
def describe_pet(animal, name):
print(f"{name} is a {animal}.")
describe_pet("dog", "Bruno") # animal="dog", name="Bruno"Keyword Arguments
Keyword arguments are passed using the parameter name, so order no longer matters. This makes function calls clearer, especially when a function has many parameters.
describe_pet(name="Bruno", animal="dog") # order doesn't matter hereDefault Arguments
A default argument has a value already assigned in the function definition. If the caller does not supply that argument, Python quietly falls back to the default — useful for optional settings.
def describe_pet(name, animal="dog"):
print(f"{name} is a {animal}.")
describe_pet("Bruno") # uses default animal="dog"
describe_pet("Whiskers", "cat") # overrides the defaultArbitrary Arguments
When you do not know in advance how many values will be passed, use *args (arbitrary positional arguments) or **kwargs (arbitrary keyword arguments). These are covered in depth in the *args and **kwargs guide, but here is a quick preview.
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3, 4)) # 10Argument Order Rules
Python enforces a strict order when you mix argument types in a single function definition. Getting this wrong raises a SyntaxError, so it is worth memorizing.
| Order | Type | Example |
|---|---|---|
| 1 | Standard positional | def f(a, b) |
| 2 | Default arguments | def f(a, b=5) |
| 3 | *args (arbitrary positional) | def f(a, *args) |
| 4 | Keyword-only arguments | def f(*args, key) |
| 5 | **kwargs (arbitrary keyword) | def f(a, **kwargs) |
You cannot place a positional argument after a keyword argument in a function call, like f(a=1, 2) — Python will raise a SyntaxError.
