# Writing Functions¶

You're probably already familiar with usingfunctions, but how do you write you own?

In Python we do this using the following structure:

def function_name(inputs):
commands
return output_value



The def tells Python that we're creating a function, the function_name is how we refer to the function in our program, the commands control what the function does with the inputs, and the return statement 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_lbs_to_kg(weight_lbs):
weight_kg = weight_lbs / 2.20462
return weight_kg


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

In [2]:
convert_lbs_to_kg(22)

Out[2]:
9.979044007584074

## Define Functions Before Calling Them¶

In the same way that we have to define a variable before we call it, we also have to define a function before we call it. So, the def statement must appear in the program before the function is used.

## Local Variables¶

Variables created inside a Python function only exist inside that function. For example, if we define our weight conversion function, and then call it, the variable weight_kg does not exist after the function has been called.

In [1]:
def convert_lbs_to_kg(weight_lbs):
weight_kg = weight_lbs / 2.20462
return weight_kg
result = convert_lbs_to_kg(170)
print weight_kg

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/home/ethan/Dropbox/Teaching/ProgBiol/repo/ipynbs/<ipython-input-1-e6d100b8310b> in <module>()
3     return weight_kg
4 result = convert_lbs_to_kg(170)
----> 5 print weight_kg

NameError: name 'weight_kg' is not defined