Python Function Parameters
Introduction
Function parameters are a crucial concept in Python programming that allow us to make our functions flexible and reusable. Parameters are the variables listed in a function definition, while arguments are the values passed to the function when it's called. Understanding how to work with parameters lets you create versatile functions that can handle different inputs and situations.
In this tutorial, we'll explore different types of parameters in Python functions, how to use them effectively, and best practices for writing clean, readable code.
Basic Function Parameters
Let's start with the simplest form of function parameters:
def greet(name):
"""A simple function with one parameter"""
return f"Hello, {name}!"
# Calling the function with an argument
result = greet("Alice")
print(result) # Output: Hello, Alice!
In this example, name
is a parameter, and "Alice"
is the argument we pass when calling the function.
Multiple Parameters
Functions can have multiple parameters separated by commas:
def describe_person(name, age, occupation):
"""A function with multiple parameters"""
return f"{name} is {age} years old and works as a {occupation}."
# Calling the function with multiple arguments
print(describe_person("Bob", 30, "developer"))
# Output: Bob is 30 years old and works as a developer.
Default Parameter Values
You can assign default values to parameters, making them optional when the function is called:
def greet_user(name, greeting="Hello"):
"""A function with a default parameter value"""
return f"{greeting}, {name}!"
# Using the default value
print(greet_user("Charlie")) # Output: Hello, Charlie!
# Overriding the default value
print(greet_user("Diana", "Good morning")) # Output: Good morning, Diana!
Important notes about default parameters:
- Parameters with default values must come after parameters without default values
- Default values are evaluated only once when the function is defined
Common Mistake with Mutable Default Values
Be careful when using mutable objects (like lists or dictionaries) as default values:
# Problematic approach
def add_item(item, item_list=[]):
item_list.append(item)
return item_list
print(add_item("apple")) # Output: ['apple']
print(add_item("banana")) # Output: ['apple', 'banana'] - Not a fresh list!
# Better approach
def add_item_better(item, item_list=None):
if item_list is None:
item_list = []
item_list.append(item)
return item_list
print(add_item_better("apple")) # Output: ['apple']
print(add_item_better("banana")) # Output: ['banana'] - Fresh list each time
Positional and Keyword Arguments
Python allows you to pass arguments in two ways:
Positional Arguments
Arguments are passed in the same order as parameters are defined:
def calculate_total(price, quantity, tax_rate):
return price * quantity * (1 + tax_rate)
# Arguments matched by position
total = calculate_total(19.99, 3, 0.05)
print(f"Total: ${total:.2f}") # Output: Total: $62.97
Keyword Arguments
Arguments are passed with parameter names, allowing you to specify them in any order:
def calculate_total(price, quantity, tax_rate):
return price * quantity * (1 + tax_rate)
# Arguments matched by name
total = calculate_total(tax_rate=0.05, quantity=3, price=19.99)
print(f"Total: ${total:.2f}") # Output: Total: $62.97
You can mix positional and keyword arguments, but positional arguments must come before keyword arguments:
# Valid: positional arguments first, then keyword arguments
total = calculate_total(19.99, quantity=3, tax_rate=0.05)
print(f"Total: ${total:.2f}") # Output: Total: $62.97
# Invalid - would cause an error:
# total = calculate_total(price=19.99, 3, 0.05)
Variable-Length Parameters
Sometimes you need a function that can accept a varying number of arguments. Python provides two special parameter types for this:
*args
(Variable Positional Arguments)
The *args
syntax allows a function to accept any number of positional arguments:
def sum_all(*numbers):
"""Sum any number of arguments"""
total = 0
for num in numbers:
total += num
return total
# Call with different numbers of arguments
print(sum_all(1, 2)) # Output: 3
print(sum_all(1, 2, 3, 4, 5)) # Output: 15
print(sum_all()) # Output: 0
**kwargs
(Variable Keyword Arguments)
The **kwargs
syntax allows a function to accept any number of keyword arguments:
def print_person_info(**details):
"""Print information about a person from keyword arguments"""
print("Person Details:")
for key, value in details.items():
print(f"- {key.replace('_', ' ').title()}: {value}")
# Call with different keyword arguments
print_person_info(name="Emma", age=28, occupation="Data Scientist")
# Output:
# Person Details:
# - Name: Emma
# - Age: 28
# - Occupation: Data Scientist
print_person_info(name="Frank", email="[email protected]")
# Output:
# Person Details:
# - Name: Frank
# - Email: [email protected]
Combining All Parameter Types
You can combine all types of parameters in a single function, but they must appear in this order:
- Standard positional parameters
- Parameters with default values
*args
(if needed)**kwargs
(if needed)
def create_profile(name, age, *hobbies, education="Not specified", **other_details):
profile = {
"name": name,
"age": age,
"education": education,
"hobbies": hobbies,
}
profile.update(other_details)
return profile
# Using all parameter types
profile = create_profile(
"Grace",
25,
"reading", "hiking", "painting",
education="Master's Degree",
occupation="Software Engineer",
location="New York"
)
import json
print(json.dumps(profile, indent=2))
# Output:
# {
# "name": "Grace",
# "age": 25,
# "education": "Master's Degree",
# "hobbies": [
# "reading",
# "hiking",
# "painting"
# ],
# "occupation": "Software Engineer",
# "location": "New York"
# }
Unpacking Arguments
Python allows you to unpack collections (like lists or dictionaries) to pass as arguments: