← All lessons
Python intermediate · Lesson 6 of 11

More about functions

Functions are the main way to organise a program, so they have a few more features worth knowing.

A parameter can have a default value, used when the caller leaves it out. Parameters with defaults go after the ones without.

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Ana"))
print(greet("Ben", "Hi"))
Prints
Hello, Ana!
Hi, Ben!

Arguments can be passed by name as well as by position. These are keyword arguments, and they make calls easier to read and let you skip to the one you want.

def order(item, size="medium", milk=True):
    return f"{size} {item}, milk: {milk}"

print(order("tea", milk=False))
Prints
medium tea, milk: False

*args in a def collects any number of extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dict. (The names are just a habit; the stars do the work.) That's how print() takes as many values as you like.

def total(*nums):
    return sum(nums)

def describe(**info):
    return ", ".join(f"{k}={v}" for k, v in info.items())

print(total(1, 2, 3, 4))
print(describe(name="Ana", age=31))
Prints
10
name=Ana, age=31

Scope is where a name can be seen. A variable assigned inside a function is local: it's separate from any variable with the same name outside. A function can read variables from outside (global ones), but assigning to the name inside makes a new local one. Pass values in and return them out rather than reaching outside.

count = 10

def bump():
    count = 99
    return count

print(bump(), count)
Prints
99 10

A string on the first line of a function's body is its docstring: a short description that editors and help() show. Write one for anything you share.

The mutable default trap: a default value is made once, when the def runs, not on every call. If it's a list or dict and the function changes it, the change carries over to the next call. Use None as the default and make a fresh list inside.

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

print(add_bad("egg"))
print(add_bad("milk"))

def add_good(item, basket=None):
    """Add item to basket, starting a new basket if none is given."""
    if basket is None:
        basket = []
    basket.append(item)
    return basket

print(add_good("egg"))
print(add_good("milk"))
Prints
['egg']
['egg', 'milk']
['egg']
['milk']

Practice

What does this print?

def power(base, exp=2):
    return base ** exp

print(power(3), power(2, 5))
More info

Quick reference

def f(a, b=1):b has a default value, used when it's left out.
f(b=2, a=1)Keyword arguments: passed by name, any order.
*args / **kwargsCollect extra positional arguments (tuple) / keyword arguments (dict).
local / globalMade inside the function / at the top level of the file.
docstringA string first in the body that describes the function.
param=NoneThe safe default for a list or dict; make a fresh one inside.

Related courses