Skip to content
Topic 6 of 6

Functions

Package code into reusable functions with def, pass arguments, return values and understand scope.

25 min read 4 pages 5 practice games Jump to practice ↓

Page 1

Defining and calling functions

A function is a named block of code that does one job. You define it once and call it as many times as you need, which keeps your program short and avoids repeating yourself.

You define a function with the def keyword, followed by the function's name, parentheses and a colon. The indented lines under it are the function body.

python
def greet(name):
    print("Hello,", name)

greet("Ada")    # Hello, Ada
greet("Grace")  # Hello, Grace

Defining a function does not run it. The body only runs when you call the function by writing its name followed by parentheses.

The names inside the parentheses of a def line are parameters. The values you pass in when you call the function are arguments. In the example above, name is a parameter and "Ada" is an argument. A function can have no parameters, one parameter or many, separated by commas.

Calling a function with the wrong number of arguments raises a TypeError.

Page 2

return vs print

The return statement sends a value back to the caller and ends the function immediately. The caller can store that value in a variable or use it in an expression.

python
def square(x):
    return x * x

result = square(4)
print(result + 1)   # 17

print() is a built-in function, not a keyword. It only shows a value on the screen; the caller gets nothing it can use. A function with no return statement returns None.

python
def show_square(x):
    print(x * x)

value = show_square(4)   # prints 16
print(value)             # None

Any code after a return statement in the same block never runs. A function can return several values separated by commas; Python packs them into a tuple.

python
def min_max(numbers):
    return min(numbers), max(numbers)

low, high = min_max([3, 9, 1])   # low is 1, high is 9

Page 3

Default parameters and keyword arguments

A default parameter has a value in the def line, so the caller can leave it out.

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

print(power(3))      # 9
print(power(3, 3))   # 27

Parameters with defaults must come after parameters without defaults; otherwise Python raises a SyntaxError.

Arguments matched by their position are positional arguments. A keyword argument names the parameter it is for, like exponent=3, so its order does not matter.

python
print(power(exponent=3, base=2))   # 8

Positional arguments must come before keyword arguments in a call.

Default values are evaluated only once, when the def statement runs. That is why a mutable default such as an empty list is shared between calls. Use None as the default and create the list inside the function instead.

Page 4

Scope and docstrings

A variable's scope is the part of the program where it can be seen. A variable created inside a function is a local variable: it exists only while the function runs and cannot be seen from outside. A variable created at the top level of a file is a global variable, and any function can read it.

python
count = 0          # global

def add_one():
    total = 5      # local
    return total + count

print(add_one())   # 5
print(total)       # NameError: name 'total' is not defined

If a function assigns to a name, that name is local to the whole function. To change a global variable inside a function, declare it with the global keyword first. Python looks up names in the order local, enclosing, global, built-in, known as the LEGB rule.

python
count = 0

def increment():
    global count
    count += 1

increment()
print(count)   # 1

A docstring is a string literal written as the first statement in a function body. It describes what the function does, and help() and the __doc__ attribute show it. PEP 257 recommends triple double quotes for docstrings.

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

Finished reading?

Mark it as read for +20 XP. Optional: practice is open either way.

Practice

Pass any one game to finish the course.

Sign in to play, save your best and unlock Topics.
  • Reach −1,500 m
  • Reach 150 km
  • 7/10 without falling
  • Clear both boards
  • 150 points

Learn more