Writing Functions

Functions help you remove redundant code by giving a name to a sequence of repeated steps. If you find yourself pasting the same code in multiple places, you will probably be better off putting the code into a function.

Step 1: Decide inputs and outputs

Write the test. The test is where you decide the inputs and outputs of the function.

x = 1
y = 2

f(x, y) == 3

Step 2: Prototype body

Prototype the body of the function. Sometimes it helps to describe the steps using pseudocode first.

x = 1
y = 2

x + y

Step 3: Define function

Move the body into the function definition and run the test.

def f(x, y):
    return x + y

x = 1
y = 2

f(x, y) == 3

Note that in languages like Python, nearly everything can be a variable. For example, here is a function that doubles the elements of a series.

def f(x):
    return x * 2

from pandas import Series
x = Series([1, 2])
f(x)

Step 4: Move function to a package

You can share functions across notebooks and scripts by using packages.