1. Functions
You already know what functions are and how to use them. In this lesson, you will write your own functions in Python.
2. Simple function
To define your own function in Python, you use the def keyword followed by the name of the function.
Inside the parentheses, you specify the parameters the function can take, and end the line with a colon.
The body of the function is indented, just like with if statements and loops, and typically will end with a return statement. Unlike R, the return statement is required if you want the function to return a value,
the last executed line of the function will not automatically be returned.
You can now make use of your own function by calling the function with the required arguments.
3. Reusing functions
The purpose of a function is so you can reuse it and minimize writing the same code again and again.
You can write functions that call other functions.
Here we have defined two functions: my_sq() and my_sq_mean(). my_sq() takes a single parameter, x,
and returns the square of x. my_sq_mean() then uses this function to return the mean square of y and z.
4. Lambda functions
Another way you can create functions is by writing a lambda function.
These are the same as anonymous functions in R, the ones you usually use in sapply(), lapply() etc..
You will typically use lambda functions with the apply method, which we will cover later.
To define a lambda function, use the lambda keyword, followed by the parameter name and colon.
You can then define the body of the function.
You can also choose to save the lambda function and use it just like a regular function.
5. Let's practice!
You'll see an application for lambda functions in later exercises, but for now, let's practice writing functions.