Perhaps, in the near future, you may want to define a function for a sequence of calculations needed to be executed in your analysis on multiple occaisions. Functions make code and statistics more concise and efficient. Having such a skill will exponentially increase your capacity to read and analyse data.
By the end of this notebook you will be able to:
Additionally, you can watch this video that explains how to make your own functions.
def f(x):
print(x)
def tells Python that you are writing a function definition. This line of code is also followed by a colon.
f is the name of the function so that the user can call the function later on.
x within the parenthesis are parameters passed into the function to be used.
## Suppose we have the following string
x = "I am X"
## We can call our function f on x variable
f(x)
I am X
def print_greeting():
print('Hello!')
# call the previous function print_greeting
print_greeting()
Hello!
## Suppose we have a function that multiply 10 to a given integer
def multiplyten(x):
x = x*10 # In this line, we are assigning a new value to x
return x # Return is what the function will give back
# now lets call the function mutiplyten
multiplyten(5)
50
EXERCISES - 5 min
1. Suppose we have the following String variable:
y = "You just called a function on y"
Please, write a function f()
in python code that prints the above y
string variable.
2. Suppose we have a function that adds 5 to a given integer as following:
def addFive(x):
x = x + 5
return x
What does this return?
5 + addFive(5)
3. Write a function bmi(height, weight)
that returns the Body Mass Index (BMI).