Python Function Parameters
In this page:
def function_name(parameter1, parameter2):
# body
function_name(argument1, argument2)
function_name(parameter2=value, parameter1=value)
What are Parameters and Arguments?
Parameters are the placeholder names listed in a function's definition, while arguments are the actual values supplied when the function is called — the distinction matters because parameters describe the function's interface, arguments fill it in for one specific call.
Example: What are Parameters and Arguments?
def greet(name): # name is the parameter
print("Hello,", name)
greet("Alex") # "Alex" is the argument
Positional Arguments
By default, Python matches arguments to parameters by position — the first argument fills the first parameter, and so on — so the order you pass values in a call must line up with the order they were defined.
Example: Positional Arguments
def describe(animal, sound):
print(animal, "says", sound)
describe("Cat", "Meow") # "Cat" fills animal, "Meow" fills sound, by position
Keyword Arguments
Passing name="value" explicitly by parameter name, instead of relying on position, lets you supply arguments in any order and makes a call self-documenting, since the parameter name is visible right at the call site.
Example: Keyword Arguments
def describe(animal, sound):
print(animal, "says", sound)
describe(sound="Meow", animal="Cat") # order doesn't matter when using keyword arguments
Modifying Mutable Parameters
Because lists and dictionaries are mutable, passing one into a function and modifying it inside (like calling .append()) changes the original object the caller still holds — unlike passing a number or string, which can't be altered in place.
Example: Modifying Mutable Parameters
def add_item(cart):
cart.append("apple") # mutates the list object passed in
cart = []
add_item(cart)
print(cart) # shows the change, since lists are mutable and shared by reference
Positional-Only and Keyword-Only Parameters
A / in the parameter list forces everything before it to be passed positionally, and a * forces everything after it to be passed by keyword only — both are optional safeguards that make a function's calling convention explicit and harder to misuse.
Example: Positional-Only and Keyword-Only Parameters
def greet(name, /, *, greeting): # / forces name to be positional, * forces greeting to be keyword
print(greeting, name)
greet("Alex", greeting="Hi")
- Passing the wrong number of arguments, e.g. calling
add(1)fordef add(a, b), which raisesTypeError. - Putting a positional argument after a keyword one, as in
f(a=1, 2), which is aSyntaxError. - Modifying a list parameter inside the function and being surprised the caller's list changed too, since lists are passed by reference.
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: