Skip to content

Functions: parameters, return and defaults

BeginnerLesson 8 of 147 min

Write your own Python functions with def: take parameters, give a result back with return, add default values and explain the function in a docstring.

A function is a piece of code with a name, which you can run (call) whenever you need it. def makes one:

def greet(name):
    print(f"Hi, {name}!")

greet("Sam")
greet("Noor")

name is a parameter: a name that, inside the function, stands for whatever value the caller passed in (the argument).

return

print shows a value; return hands it back to whoever called the function, so they can keep using it:

def area(width, height):
    return width * height

kitchen = area(3, 4)
print(kitchen + area(2, 2))   # 16

return also ends the function at once. A function that never reaches a return gives back None: try print(greet("Sam")) above and see None printed after the greeting.

Defaults and keyword arguments

A parameter with = has a default, used when the caller leaves it out. Callers can also name arguments, in any order:

def brew(tea, minutes=3, milk=False):
    return f"{tea}, {minutes} min" + (", with milk" if milk else "")

print(brew("green"))
print(brew("black", 5, milk=True))
print(brew("rooibos", milk=True))

Parameters with defaults come after the ones without.

Docstrings

A string on the first line of a function is its docstring: what it does, for the people who use it. help() shows it:

def area(width, height):
    """Return the area of a rectangle."""
    return width * height

help(area)

Tip:The Advanced lesson on names shows one trap with defaults: never use a list or dict as a default value.

More in the Python docs: defining functions, default argument values and docstrings.

Your turn

Write a function tip(bill, percent=10) that returns the tip, rounded to 2 decimal places, and has a docstring. tip(40) should give 4.0 and tip(40, 15) should give 6.0. The last line prints tip(23.5, 20).

Next →