Lesson 2 of 5 · Functions · 3 min read · Updated
Function arguments
Default values, arguments by name, and functions that accept any number of values.
Defaults and keywords
def power(base, exponent=2):
return base ** exponent
print(power(5))
print(power(2, 10))
print(power(exponent=3, base=2))
25
1024
8
A default (exponent=2) is used when the caller leaves that argument out. A keyword argument names the parameter, so order no longer matters and the call explains itself.
Any number of values
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3))
print(total())
def profile(name, **details):
print(name)
for key, value in details.items():
print(f" {key}: {value}")
profile("Priya", city="Salem", age=21)
6
0
Priya
city: Salem
age: 21
*numberscollects any extra positional arguments into a tuple.**detailscollects any extra keyword arguments into a dictionary.- The names
argsandkwargsare only a convention; the stars do the work.
def distance(x, y):
return (x ** 2 + y ** 2) ** 0.5
point = (3, 4)
print(distance(*point))
5.0
Stars work the other way round in a call: *point unpacks a tuple or list into separate arguments, and **options unpacks a dictionary into keyword arguments.
The mutable default trap
def add_item(item, basket=[]):
basket.append(item)
return basket
print(add_item("pen"))
print(add_item("book"))
['pen']
['pen', 'book']
Warning
A default value is created once, when the function is defined — not on every call. So that one empty list is shared, and it keeps growing. Use None as the default and create the list inside.
def add_item(item, basket=None):
if basket is None:
basket = []
basket.append(item)
return basket
print(add_item("pen"))
print(add_item("book"))
['pen']
['book']
def f(a, b=10): return a + b. What is f(b=1, a=2)?
Try this now
- Write
make_bill(*prices, discount=0)that totals any number of prices and applies a percentage discount. - Write
describe(**info)that prints each key and value on its own line, sorted by key.
Create a free account to save your progress, or sign in.