10 Functions in Python
We’ve learned how to use built-in functions to analyze data, but sometimes it’s more helpful to (A) do the math by hand or (B) write your own function. Let’s learn how!
10.1 Coding your own function!
Functions
are machines that do a specific calculation using an input to produce a specific output.
Below, we’ll write an example function, called add(a, b)
.
This function takes two
numeric
values,a
andb
, asinputs
, and adds them together.Using
def
, we’ll tellPython
that our function contains two inputs,a
andb
.The function can involve multiple operations inside it. But at the end, you need to print one final output, or put
return
before your output.
## 3
# This also works
def add(a, b):
# Assign output to a temporary object
output = a + b
# Return the temporary object 'output'
return output
add(1, 2)
## 3