Skip to content

Functions

Batteries included

The Python documentation includes an excellent tour of the standard library.

This tutorial has made use of several built-in Python functions already, including type(), set(), len(), and range().

positional arguments

The simplest form of a function call takes one or more positional arguments. For example, the sorted() function can be called with a single positional argument

a = [ 3, 1, 5, 4, 2]

sorted(a)

This function will return a sorted version of the input list [ 1, 2, 3, 4, 5 ].

keyword arguments

If you read through the documentation for the sorted() function, you'll see that it can accept additional keyword arguments

def sorted(iterable, key=None, reverse=False)

These arguments are optional since they've been defined with the default values None and False. You can override these defaults by referencing the argument by keyword. For example, you can pass reverse=True to reverse the sort order

sorted(a, reverse=True)

Defining a function

Functions are defined using the def keyword, followed by the name of the function, followed by a comma separated list of arguments within parentheses ()

def my_function(a, b, c)

This is known as a function signature.

Implementing a function

The function's implementation should exist within an indented block directly below the function signature. You must also append a colon : to the end of the function signature

def function(a, b, c):
    print('a is', a)
    print('b is', b)
    print('c is', c)

Now you can invoke this function like any other function from the standard libary

function(1, 2, 3)

This will print the following to the console

a is 1
b is 2
c is 3

defining keyword arguments

Positional arguments are always declared first in a function signature. These arguments are required to invoke the function. If you'd like to define any optional arguments, those must be declared after the positional arguments using the keyword=default syntax

def function(a, b=8, c=16):
    print('a is', a)
    print('b is', b)
    print('c is', c)

Given the function definition above, a is required, b is optional (with a default value 8), and c is optional (with a default value 16). When calling this function, if you wish to override any of these optional keyword arguments, you can refer to them by keyword

function(1, c=3)

This will print the following text to the console

a is 1
b is 8
c is 3

Returning values

Often times you will want your function to manipulate some input data and return a result. This is done using a return statement

def function(a, b, c):
    return (a + b) / c

If your function has a return value, you can store that value within a variable using the assignment operator =

result = function(1, 2, 3)