Python Function Arguments
Python gives you flexible ways to pass values into functions. Arguments can be given by position or by name, parameters can have default values, and a function can accept any number of arguments. Knowing these forms lets you write functions that are easy and pleasant to call.
Positional and keyword arguments
By default, arguments are matched to parameters by their position. You can also name them, as keyword arguments, and then the order does not matter:
def introduce(name, age, city):
print(f"{name}, {age}, from {city}")
introduce("Asha", 21, "Pune")
introduce(city="Delhi", name="Ravi", age=25)
introduce("Meera", city="Goa", age=30)Asha, 21, from Pune Ravi, 25, from Delhi Meera, 30, from Goa
Keyword arguments make calls easier to read, especially when a function takes several numbers or booleans. Positional arguments must come before keyword arguments in a call.
Default values
A parameter with a default value can be left out when calling:
def price_with_tax(price, rate=0.18, round_to=2):
return round(price * (1 + rate), round_to)
print(price_with_tax(100))
print(price_with_tax(100, 0.05))
print(price_with_tax(99.99, round_to=0))118.0 105.0 118.0
Parameters with defaults come after those without. A warning: a default value is created once, when the function is defined. Never use a list or a dictionary as a default, like def add(item, items=[]), because every call would share and grow the same list. Use None as the default and create the list inside the function.
Any number of arguments
A parameter with one star, usually called *args, collects all extra positional arguments into a tuple. Two stars, **kwargs, collect extra keyword arguments into a dictionary:
def average(*numbers):
return sum(numbers) / len(numbers)
def profile(name, **details):
print(name)
for key, value in details.items():
print(f" {key}: {value}")
print(average(4, 8, 6))
print(average(10, 20, 30, 40, 50))
profile("Asha", age=21, city="Pune", language="Python")6.0 30.0 Asha age: 21 city: Pune language: Python
This is how print accepts any number of values. The star also works the other way when calling: average(*[1, 2, 3]) unpacks a list into separate arguments.
Keyword-only arguments
Parameters written after * in the definition can only be given by name, as in def connect(host, *, timeout=10). This forces callers to write timeout=30, which keeps the call clear.
Practice exercises
- Write
make_greeting(name, greeting="Hello")and call it with and without the second argument. - Write
total(*prices)that returns the sum of any number of prices. - Write
describe_pet(name, kind="dog", age=1)and call it using keyword arguments only. - Show the mutable default trap with a list default, then fix it with
None.