Function Arguments
Pass values to functions safely with positional, keyword, default, variable, and named arguments.
Ways to pass arguments
Arguments can be matched by their position or by a parameter name. A positional argument must appear in the same order as the parameters.
A keyword argument uses name=value, so its order is clear.
def introduce(name, age):
print(name, age)
introduce("Mina", 12)
introduce(age=12, name="Mina")
def introduce(name, age):
print(f"{name} is {age}.")
introduce("Mina", 12)
introduce(age=12, name="Mina")
The first call is positional: the first value goes to name and the second goes to age. The second call names both parameters, so Python can match them in either order.
Default parameter values
def welcome(name, greeting="Hello"):
print(f"{greeting}, {name}!")
welcome("Kai")
welcome("Kai", "Welcome back")
greeting has a default value. Python uses it when you do not provide that argument, and uses your value when you do.
Avoid mutable default values
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("tea"))
print(add_item("coffee"))
def show_order(item, *extras, **details):
print(item)
print(extras)
print(details)
show_order("Book", "Bookmark", "Pen", priority="high", gift=True)
*extras collects extra positional arguments in a tuple. **details collects extra keyword arguments in a dictionary.
Key points
- Positional arguments match parameter order.
- Keyword arguments name the parameter they fill.
- Defaults make an argument optional.
- Do not use a list or dict as a default value.
- *args and **kwargs collect extra arguments.
Worked example
A cinema booking: seat number is required, but the snack bundle is optional and can be passed by keyword for clarity.
def book(name, show, snack=None):
line = f"{name}: {show}"
if snack:
line += f" + {snack}"
return line
print(book("Rafi", "7pm", snack="popcorn"))
How it works, step by step
- Positional arguments fill parameters in order: name then show.
- snack=... was passed by KEYWORD, so its label makes the call self-documenting.
- The default None lets callers skip it.
References & Further Reading
Related entries from PyLabs's own reference library.
Practice exercise
Not passed yetWrite a function named repeat with parameters word and times=2. Print word repeated times times. Call repeat("go", 3).
Expected output: gogogo
# Write your code below
Check yourself
Function Arguments quiz
10 questions. You get instant feedback per question, and the timer starts when you press the button.
Lesson incomplete
Not completedCreate an ID or sign in to save lesson completion across devices.