Python Functions

By

Published · Updated

Tagged: Python

Learn how functions work in Python: how to define one with def, pass parameters and default values, return one or more values, and call it from your code.

A function lets us create a set of instructions that we can run when needed.

Functions are essential in Python and in many other programming languages to create meaningful programs, because they allow us to decompose a program into manageable parts, they promote readability and code reuse.

Here is an example function called hello that prints “Hello!”:

def hello():
    print('Hello!')

This is the function definition. There is a name (hello) and a body, the set of instructions, which is the part that follows the colon and it’s indented one level on the right.

To run this function, we must call it. This is the syntax to call the function:

hello()

We can execute this function once, or multiple times.

The name of the function, hello, is very important. It should be descriptive, so anyone calling it can imagine what the function does.

A function can accept one or more parameters:

def hello(name):
    print('Hello ' + name + '!')

In this case we call the function passing the argument

hello('Roger')

We call parameters the values accepted by the function inside the function definition, and arguments the values we pass to the function when we call it. It’s common to get confused about this distinction.

A parameter can have a default value that’s applied if the argument is not specified:

def hello(name='my friend'):
    print('Hello ' + name + '!')

hello()
#Hello my friend!

Here’s how we can accept multiple parameters:

def hello(name, age):
    print('Hello ' + name + ', you are ' + str(age) + ' years old!')

In this case we call the function passing a set of arguments:

hello('Roger', 8)

You can also pass arguments by name. The order then does not matter:

hello(age=8, name='Roger')

Python passes a reference to the object (pass by assignment). Reassigning the parameter inside the function never changes the caller’s variable, mutable or not:

def change(value):
    value = 2

val = 1
change(val)

print(val) #1

Mutating a mutable object is visible outside. Here items.append(3) changes the same list:

def add_item(items):
    items.append(3)

numbers = [1, 2]
add_item(numbers)

print(numbers) #[1, 2, 3]

The name items inside the function points at the same list. I wrote more about objects and scope.

Be careful with a mutable default, like a list. Python creates that list once, when it defines the function. Every call that skips the argument reuses the same list:

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

add_item('apple') #['apple']
add_item('pear') #['apple', 'pear']

The second call still sees 'apple'. Use None as the default and create the list inside:

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

A function can return a value, using the return statement. For example in this case we return the name parameter name:

def hello(name):
    print('Hello ' + name + '!')
    return name

When the function meets the return statement, the function ends.

We can omit the value:

def hello(name):
    print('Hello ' + name + '!')
    return

We can have the return statement inside a conditional, which is a common way to end a function if a starting condition is not met:

def hello(name):
    if not name:
        return
    print('Hello ' + name + '!')

If we call the function passing a value that evaluates to False, like an empty string, the function is terminated before reaching the print() statement.

You can return multiple values by using comma separated values:

def hello(name):
    print('Hello ' + name + '!')
    return name, 'Roger', 8

In this case calling hello('Syd') the return value is a tuple containing those 3 values: ('Syd', 'Roger', 8).

Want me to talk about your product? You can sponsor this site.

Related posts about python: