Writing Functions

We've already been using functions, but how do you write them on your own?

In Python we do this using the following structure:

def function_name(inputs):
    return output_value

  • def tells Python that we're creating a function
  • function_name is how we refer to the function in our program
  • the commands control what the function does with the inputs
  • return tells Python what output to send back to the rest of the program.

Then indentation is important because it tells Python what is inside the function. You end a function by stopping the indenting.

For example, if we wanted to write a function that converts pounds to kilograms:

In [1]:
def convert_kg_to_g(weight_kg):
    weight_g = weight_kg * 1000
    return weight_g

We can then call that function exactly like we would one of Python's built in functions:

In [2]:

Functions can have multiple inputs

Let's say we've fit a linear regression to some data and want to get a prediction based on the fitted parameters.

In [3]:
def predicted_value(a, b, x):
    prediction = a + b * x
    return prediction

predicted_value(2, 1, 1)

Define Functions Create Instructions

  • Defining a function creates a set of instructions, but doesn't do anything with them
  • Like describing to a friend how to make a PB&J sandwhich
  • When you call the function the computer follows those instructions and creates a value
  • If you want to do something with that value you need to store it in a variable
  • Functions need to be defined before they are called.

Local Variables

Variables created inside a Python function only exist inside that function.

In [4]:
def convert_kg_to_g(weight_kg):
    weight_g = weight_kg * 1000
    return weight_g
result = convert_kg_to_g(3.9)
print weight_g
NameError                                 Traceback (most recent call last)
<ipython-input-4-e642eed7c18d> in <module>()
      3     return weight_g
      4 result = convert_kg_to_g(3.9)
----> 5 print weight_g

NameError: name 'weight_g' is not defined

You should also treat functions as if they don't know about variables outside of them, so they should only work with things that you pass them as input.