Functions
In the next couple lessons we'll cover something cool called functions.
Functions are basically mini-programs inside of your program.
They're neat because they can run a piece of code just by using their name. So it saves you from typing code over and over again.
There are 4 types of functions we'll learn about:
By "return" I mean that they can send a value back to the main body of code that you used or "called" out the function in.
So let's call our original program "main". Let's call our functions FunA, FunB and FunC.
Remember our functions are mini programs inside of our main program.
So I can use FunA, and I can give it the ability to interact directly with main or not at all.
The 4 things it can do is (this is just rewording what the 4 function types can do):
Try the following program:
The output will look like this:
Note: Not a lot of people write #main. This is the way I learned it but you don't have to put it in.
This is a good way of marking where your main program is. You should GROUP all your functions at the top of your program, and the main body of your program after.
#main is a way of saying that everything below is your main body of your program and there are no more functions to define.
From the results you can see just by typing in the name of the function I defined, I can activate what's inside of the function.
To make a function you need 3 things:
Here's another example program for you to try. This is a program that calls out the function called randomnumber whenever it wants to get a random number. Note that the random number that it generates only exists in the function and does not get returned to main! So it just shows a random number and that's it.