2.4 Introduction to functions
This is a very short introduction to functions.
We will soon go into more detail on functions, in the page on call expressions.
For now, we start with something simple, the function cos
.
Remember functions from mathematics? We might write something like this, in mathematics:
\[y = cos(0)\]You can read $cos(0)$ as:
Call the function “cos” with the value 0, and return the result.
Then $y = cos(0)$ means:
Call the function “cos” with the value 0, and return the result, storing the result in “y”.
We pass a value to the function. In our case we pass the value $0$.
The function returns a value. In our case it returns the calculation of the cosine of $0$.
You may remember that the cosine of 0 is 1. So, after $y = cos(0)$, we expect $y$ to equal 1.
Functions in Python work in a similar way.
First we load up the cos
function from a library called numpy
.
Don’t worry about the command to load the function, for now. We will come back to that later. Here is the command you need. Just run it in the notebook.
# Get the cos function from the numpy library.
from numpy import cos
Now we call the cos
function with the value 0, and see what we get:
cos(0)
1.0
cos
is the name of the function;0
is the value we as passing to the function.- The value we pass to the function goes between the parentheses
(
and)
. 1.0
is the value that the function returns.
The value we pass to the function is also called the function argument.
In our case we pass 0
as the argument to the cos
function.
Let’s try the same thing with the sin
function:
# Get the sin function from the numpy library.
from numpy import sin
sin(0)
0.0
sin
- the function name;0
- the value we pass to the function;- The value goes after the function name, and between parentheses;
0.0
- the value that the function returns.
We pass 0
as the argument to the sin
function.
Now your turn.
Try importing the sqrt
function.
# Get the sqrt function from the numpy library.
# Your code here.
Call the sqrt
function with the value 9
; you should see this returns the value 3.0
.
# Your code here.
We will see more about functions in the section on call expressions.