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):
commands
return output_value
def
tells Python that we're creating a functionfunction_name
is how we refer to the function in our programinputs
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:
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:
convert_kg_to_g(2.2)
2200.0
Let's say we've fit a linear regression to some data and want to get a prediction based on the fitted parameters.
def predicted_value(a, b, x):
prediction = a + b * x
return prediction
predicted_value(2, 1, 1)
3
Variables created inside a Python function only exist inside that function.
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.