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

python
def power(base, exponent=2):
    return base ** exponent

print(power(5))
print(power(2, 10))
print(power(exponent=3, base=2))
Output
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

python
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)
Output
6
0
Priya
  city: Salem
  age: 21
  • *numbers collects any extra positional arguments into a tuple.
  • **details collects any extra keyword arguments into a dictionary.
  • The names args and kwargs are only a convention; the stars do the work.
python
def distance(x, y):
    return (x ** 2 + y ** 2) ** 0.5

point = (3, 4)
print(distance(*point))
Output
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

python
def add_item(item, basket=[]):
    basket.append(item)
    return basket

print(add_item("pen"))
print(add_item("book"))
Output
['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.

python
def add_item(item, basket=None):
    if basket is None:
        basket = []
    basket.append(item)
    return basket

print(add_item("pen"))
print(add_item("book"))
Output
['pen']
['book']

def f(a, b=10): return a + b. What is f(b=1, a=2)?

Try this now

  1. Write make_bill(*prices, discount=0) that totals any number of prices and applies a percentage discount.
  2. 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.