Table of Contents
Parameters and Arguments
In this chapter, you’ll see how to give information to functions using parameters and arguments. This is what makes functions truly reusable and flexible.
Parameters vs Arguments
When talking about functions:
- Parameters are the names listed in a function’s definition.
- Arguments are the actual values you pass when you call the function.
Think of a function like a machine:
- Parameters = labeled input slots on the machine.
- Arguments = the actual items you put into those slots.
def greet(name): # 'name' is a parameter
print("Hello,", name)
greet("Alice") # "Alice" is an argument
greet("Bob") # "Bob" is an argument
The function greet is defined with one parameter: name.
Each time you call greet(...), you pass a different argument.
Positional Arguments
The most common type of arguments are positional arguments.
They are matched to parameters by their position (order).
def add(a, b):
print(a + b)
add(3, 5) # a = 3, b = 5
add(10, 2) # a = 10, b = 2- First argument → first parameter (
a) - Second argument → second parameter (
b)
If you change the order, the meaning changes:
def describe_pet(animal, name):
print("I have a", animal, "named", name)
describe_pet("dog", "Rex") # animal = "dog", name = "Rex"
describe_pet("Rex", "dog") # animal = "Rex", name = "dog" (probably wrong!)With positional arguments, order matters.
Keyword Arguments
Keyword arguments (also called named arguments) use the parameter name when calling the function. This makes your call more explicit and order-independent.
def describe_pet(animal, name):
print("I have a", animal, "named", name)
describe_pet(animal="dog", name="Rex")
describe_pet(name="Mittens", animal="cat")In both calls:
animalgets"dog"or"cat"namegets"Rex"or"Mittens"
Here, the order does not matter, because you specify which value goes to which parameter by name.
You can mix positional and keyword arguments, but:
- Positional arguments must come first.
- Keyword arguments come after.
def introduce(first_name, last_name, age):
print(first_name, last_name, "is", age, "years old.")
introduce("Alice", "Smith", 20) # all positional
introduce("Alice", last_name="Smith", age=20) # mixed: positional then keyword
# introduce(first_name="Alice", "Smith", 20) # ❌ not allowed (positional after keyword)Default Parameter Values
Sometimes you want parameters to have a default value, which will be used if the caller does not provide an argument.
You define default values in the function definition using =.
def greet(name, greeting="Hello"):
print(greeting + ",", name)
greet("Alice") # uses default greeting "Hello"
greet("Bob", "Good morning") # overrides default greeting- If
greetingis not given, it uses"Hello". - If an argument is given for
greeting, that value is used instead.
You can also combine positional, keyword, and default parameters:
def make_sandwich(bread, filling="cheese", toasted=False):
print("Bread:", bread)
print("Filling:", filling)
print("Toasted:", toasted)
make_sandwich("white") # uses defaults for others
make_sandwich("whole grain", "ham") # change filling
make_sandwich("white", toasted=True) # keyword for toasted
make_sandwich("rye", filling="turkey", toasted=True)Rule about defaults
Parameters with default values must come after parameters without defaults in the function definition:
def example(a, b=10): # ✅ allowed
pass
# def wrong_example(a=10, b): # ❌ not allowed (non-default after default)
# passMultiple Parameters
You can define functions with more than one parameter. Each one needs an argument when calling the function (unless it has a default).
def calculate_total(price, quantity, tax_rate):
subtotal = price * quantity
tax = subtotal * tax_rate
total = subtotal + tax
print("Total:", total)
calculate_total(10.0, 3, 0.1) # all positional
calculate_total(price=10.0, quantity=3, tax_rate=0.1) # all keyword
calculate_total(10.0, tax_rate=0.1, quantity=3) # mixed with keywords
If a parameter has no default and you do not provide an argument, Python will raise a TypeError.
def show_info(name, age):
print(name, "is", age, "years old.")
# show_info("Alice") # ❌ missing argument for 'age'Variable Number of Arguments: `*args` and `**kwargs`
Sometimes you don’t know in advance how many arguments you’ll need. Python lets you collect a variable number of arguments using args and *kwargs.
`*args` – extra positional arguments
Use *args to accept any number of extra positional arguments. Inside the function, args will be a tuple.
def add_all(*numbers):
total = 0
for n in numbers:
total += n
print("Sum:", total)
add_all(1, 2) # numbers = (1, 2)
add_all(1, 2, 3, 4, 5) # numbers = (1, 2, 3, 4, 5)
*numbers means: “pack all extra positional arguments into a tuple called numbers.”
You can mix normal parameters and *args:
def greet_all(greeting, *names):
for name in names:
print(greeting, name)
greet_all("Hello", "Alice", "Bob", "Charlie")Here:
greetinggets the first argument.- All remaining arguments go into
names.
`**kwargs` – extra keyword arguments
Use kwargs to accept any number of extra keyword arguments. Inside the function, kwargs will be a dictionary**.
def print_settings(**options):
for key, value in options.items():
print(key, "=", value)
print_settings(volume=10, brightness=70, theme="dark")Here, inside the function:
optionsis a dictionary like{"volume": 10, "brightness": 70, "theme": "dark"}.
You can mix normal parameters, args, and *kwargs:
def demo(a, b, *args, **kwargs):
print("a:", a)
print("b:", b)
print("args:", args)
print("kwargs:", kwargs)
demo(1, 2, 3, 4, x=10, y=20)Call result:
a = 1b = 2args = (3, 4)kwargs = {'x': 10, 'y': 20}
Order of different parameter types
When defining a function, the general order is:
- Regular positional parameters
- Parameters with default values
*args**kwargs
Example:
def func(a, b=0, *args, **kwargs):
passArgument Unpacking with `*` and `**`
The and symbols are also used when calling* functions to unpack collections into arguments.
Unpacking a list or tuple into positional arguments
You can pass a list or tuple to a function as separate positional arguments using *:
def multiply(a, b, c):
print(a * b * c)
numbers = [2, 3, 4]
multiply(*numbers) # same as multiply(2, 3, 4)
*numbers unpacks the list into separate arguments.
Unpacking a dictionary into keyword arguments
You can pass a dictionary to a function as separate keyword arguments using **:
def greet_person(name, greeting, punctuation):
print(greeting, name + punctuation)
data = {
"name": "Alice",
"greeting": "Hi",
"punctuation": "!"
}
greet_person(**data) # same as greet_person(name="Alice", greeting="Hi", punctuation="!")Here, the dictionary keys must match the parameter names.
Common Beginner Mistakes with Parameters and Arguments
1. Wrong number of arguments
Providing too many or too few arguments:
def f(x, y):
print(x, y)
# f(10) # ❌ missing 'y'
# f(10, 20, 30) # ❌ too many arguments2. Mixing up positions
Assuming order doesn’t matter with positional arguments:
def login(username, password):
print("Username:", username)
print("Password:", password)
login("mypassword", "me") # order swapped, likely wrongUse keyword arguments to avoid this:
login(username="me", password="mypassword")3. Using mutable default values (advanced warning)
Avoid using mutable objects like lists or dictionaries as default values; they can behave in surprising ways. For beginners, a safe rule:
- Use
Noneas a default, then create the list/dict inside the function.
def add_item(item, collection=None):
if collection is None:
collection = []
collection.append(item)
return collectionYou don’t need to fully understand why yet, just remember this pattern when you need a “default list” or similar.
Practice Ideas
Try writing functions with different kinds of parameters:
- A function
area_of_rectangle(width, height)that takes two positional arguments. - A function
greet_user(name, greeting="Hello")using a default parameter. - A function
average(*numbers)that computes the average of any number of values. - A function
show_profile(name, **details)that prints the user’s name and any extra information (age, city, hobby, etc.) given as keyword arguments.
Parameters and arguments are the main way to control what your functions do. With them, you can write a function once and use it in many different situations by passing different values.