When you program in Scratch you may create many scripts, each one designed to do a specific job in your program.
Good programmers structure their code to keep it well oganised.
One way of doing this is to make use of functions.
A function is a collection of code that will only run when it is 'called' on by the main program.
It is much easier to plan, to understand and to debug your program if you keep all of the code that performs a particular job together in one place by defining (creating) a function.
They improve the efficiency of your code.
Functions can be used over and over again, they can also be saved and used in your other programs.
If you have not done so yet, click on the link below to see the fly function being used to make the butterfly sprite fly.
Each time the space bar is pressed the program will call the fly function and its code will run - the butterfly will fly - but only when the function is called.
Otherwise the function will just sit in the program doing nothing until it is called by the main program.
It was created using a pink block from My Blocks.
You must first Make a Block and give it a short name that reminds you what it does. You may end up with many different functions in your program.
In this example, the function is called 'fly' because it makes the buterfly fly.
Finally, define the function by creating its script.
You can make a function to do anything you like.
In this program, every time the space bar is pressed the fly function will be called and the code in the function will run.
The butterfly will fly around 5 times, return to the cat and then play a tune.
We only have to create this function once, but we can use it as many times as we like.
Each time the space bar is pressed the butterfly will take off.
When you create Scratch scripts in the future, try to organise your code into functions.
Always give your function a name that reminds you what it does.
You can create as many functions as you like.
Q41. What are four main benefits of using functions in your programming?
Q42. Explain what happens when a program 'calls' a function.