Function Parameters
A function that does exactly the same thing every time is useful, but limited. What if you want to greet different people by name? Or calculate tax for different amounts? Parameters let you pass information into functions, making them flexible and reusable.
Adding a Parameter
Parameters go inside the parentheses when you define a function:
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Hello, Alice!
greet("Bob") # Hello, Bob!
Here, name is a parameter — a variable that receives a value when the function is called. The values "Alice" and "Bob" are arguments — the actual data you pass in.
Think of parameters as empty boxes waiting to be filled. Arguments are what you put in those boxes.
Multiple Parameters
Functions can accept multiple parameters, separated by commas:
def greet(name, greeting):
print(f"{greeting}, {name}!")
greet("Alice", "Hello") # Hello, Alice!
greet("Bob", "Good morning") # Good morning, Bob!
The order matters — the first argument fills the first parameter, the second fills the second, and so on.
Default Values
Sometimes you want a parameter to have a fallback value if the caller doesn't provide one:
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice") # Hello, Alice! (uses default)
greet("Alice", "Hi") # Hi, Alice! (overrides default)
Parameters with defaults must come after parameters without defaults.
A Practical Example
def calculate_total(price, quantity, tax_rate=0.08):
subtotal = price * quantity
tax = subtotal * tax_rate
total = subtotal + tax
print(f"Subtotal: ${subtotal:.2f}")
print(f"Tax: ${tax:.2f}")
print(f"Total: ${total:.2f}")
calculate_total(29.99, 3) # Uses default 8% tax
calculate_total(29.99, 3, 0.10) # Uses 10% tax
This single function handles different prices, quantities, and tax rates — far more useful than hardcoding values.
Parameter vs Argument
These terms are often used interchangeably, but technically:
- Parameter: The variable name in the function definition (
name,greeting) - Argument: The actual value passed when calling (
"Alice","Hello")
You define parameters; you pass arguments.
Why This Matters
Parameters transform functions from rigid scripts into flexible tools. Instead of writing separate functions for every variation, you write one function that adapts to different inputs. This is fundamental to writing clean, maintainable code.