Skip main navigation

Defining a function

This article will give a brief definition of a function within Python.
Every function has a name and some number (possibly zero) of parameters. The syntax to define a function is as follows:

def <function_name>(<parameters>):

<statements to perform when the function is called>

The def keyword tells Python that you wish to define a function. On the same line the function interface is defined, which is its name and a comma-separated list of parameters, followed by a colon. If the function has no parameters, then there is nothing inside the parentheses; however, the parentheses themselves must still be included.

The line following this must be indented, and all subsequent lines which are similarly indented belong to the body of the function. This is the code that will be executed when you come to use the function. Recall that Python relies entirely on indentation to understand code structure.

The body of the function can contain any valid Python code, including loops and conditional statements. It can even contain more function definitions. The function body ends when there is a line of code which is not indented compared to the line beginning def (or when the file ends).

Parameters are a special sort of variable. They can be used inside the function exactly like a variable, but they cannot be used outside of the function. The value of a parameter is defined when the function is called.

This article is from the free online

Python for Data Science

Created by
FutureLearn - Learning For Life

Reach your personal and professional goals

Unlock access to hundreds of expert online courses and degrees from top universities and educators to gain accredited qualifications and professional CV-building certificates.

Join over 18 million learners to launch, switch or build upon your career, all at your own pace, across a wide range of topic areas.

Start Learning now