Positional and Keyword Arguments
In this lesson, you'll learn two ways of passing arguments into functions in Python:
- Positional arguments – where the order matters
- Keyword arguments – where the name matters
Understanding this makes your functions more flexible and your code easier to read.
Positional Arguments
These are the most common. The values are passed to the function in the same order the parameters are defined.
Example:
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet("Alice", 25) # name = "Alice", age = 25
If you switch the order:
greet(25, "Alice") # name = 25, age = "Alice"
The function still runs, but now the meaning of the values is incorrect.
Keyword Arguments
With keyword arguments, you explicitly mention the parameter name in the function call.
Example:
greet(age=25, name="Alice")
- The order doesn't matter now because you're specifying what each value is for.
This can be useful when:
- You have many parameters.
- You want your code to be more readable.
- You want to skip certain default parameters.
Mixing Positional and Keyword Arguments
You can combine both, but the positional arguments must come first.
Valid
greet("Alice", age=25)
Invalid
greet(name="Alice", 25) # ? SyntaxError
Real-Life Example
Let’s say you have a function to create a profile:
def create_profile(name, age, country="Ghana"):
print(f"{name} is {age} years old and lives in {country}.")
You could call it like:
create_profile("Ahmed", 30)
create_profile("Nana", 28, "USA")
create_profile(age=45, name="Kwame", country="Canada")
Common Mistakes
- Mixing keyword and positional in the wrong order.
- Forgetting which parameter comes first in positional arguments.
- Typos in keyword names.
Exercise: Try It Yourself!
Create a function order_food(item, quantity, price)
that prints the total cost:
# Sample call:
order_food("Pizza", 2, 5) # Positional
order_food(quantity=3, item="Rice", price=4) # Keyword
Add another version where price
has a default value of 10, and try:
order_food("Burger", 2) # Uses default price
Summary
Concept | Description |
---|---|
Positional Arguments | Order matters. |
Keyword Arguments | Specify parameter names, order doesn’t matter. |
Mixing Rules | Positional must come before keyword arguments. |