Starting To Learn Functions
What are Functions¶
A function is just a block of code that is designed to run a particular task. In Unit 2 we will continue to place all our code inside functions, but it's time to look a little closer to see how they work.
Parts of a Function Declaration¶
- The function starts with the word
function
and is all the way to the left. It's not indented. - Next, comes the name of the function. In this example the name is
demoFunction
. - After the name of the function will always be a pair of parentheses,
()
. Sometimes there will be more text inside the parentheses. - Next, comes a left curly brace,
{
with a space before it. - At the end of the function is a right curly brace,
}
. It will always be on a line by itself and all the way to the left. - We write our code on the lines in between the curly braces. All our code will start indented by 4 spaces.
1 2 3 |
|
Running a Function¶
When the code is in a function, it does not run until we tell it to. We have to cause it to run by referring to the function name later. The functions themselves will be close to the top of the demo, lab, and project files. When we want to run them, we will have code like this.
We call, or invoke, the function like this:
1 2 3 4 5 6 7 |
|
Line 4 causes the function to run as if the code were right there in the first place. Sweet!
Just like in Unit 1, all the functions and function calls have been created for you. All you need to do is continue to write your code inside the function.
This is good!
Read more¶
Related Reading
Pages 23 - 30 — Now would be a good time to read this if you didn't already in Unit 1