4. Functions
What are Functions?
A function is a block of code that runs when it is called. You can think of it as a step-by-step task given to the computer to execute.
Why Functions?
Functions can help you save time by writing repeating code only once and then referring back to it whenever you need to in the code. Not only does this make your code cleaner, but it makes code run faster on your computer as well.
How do you Create Functions?
First, type in the word "def" and then the name you want for your variable. "def" stands for define, meaning you are defining a new function.
def myFunction
Then, add parentheses and a colon.
def myFunction():
Finally, add the code you want inside of the function by tabbing the line before writing your code.
def myFunction():
x = 1
print(x)
And there you go! You have just written your first Python function. But, functions have even more cool features that we will discuss throughout this lesson.
Calling a Function
Calling a function is very simple! All you need to do is type in the function name and then add parenthesis right after.
myFunction()
Function Parameters
Function parameters are the variables listed inside of the parenthesis in the function definition. You can use the parameters throughout the function to perform various tasks in the function's code. Function can have more than one parameter in the code, which you can do by separating each parameter with a comma.
def myFunction(x, y):
z = x + y
myFunction(12, 17)
Returning Values
Not only can you take parameters to use in a function, but you can also return values back into the code whenever you need to! To help you understand this concept better, let's continue on with the last function.
def myFunction(x, y):
z = x + y
In this function, we add the values we receive from both parameters together. But what if we wanted to return this value so we are able to use it somewhere else in the code?
To do that, first type in the word "return" in the function's codeblock.
def myFunction(x, y):
z = x + y
return
Then, type in whatever you want to return. It's easy as that!
def myFunction(x, y):
z = x + y
return z
Now, whenever you pass in two values when you call the function, it will return the sum of the two values. You can save return values by calling a function inside of a variable.