Functions in BlocklyProp
Functions are blocks of code that you put together to complete a specific job. Think of a function as a single block that you make so that you can use it over and over again. Just like other blocks, you can put it in your program anywhere that you need it, and as many times as you want.
With BlocklyProp, making a function is easy. Take a look at the example below:
To make a function, enclose a group of blocks with the define function block, and then give it a name. After that, in the FUNCTION menu, you will see a new run function block with that name, to use in your program. In this example, when our BlocklyProp program gets to the run function “printAge” block, it jumps to the matching define function block and runs the code inside of it. Upon completion, it jumps back, and the program continues.
Functions are handy if you have to repeat the same code in a few different places within your program. Instead of using many blocks over and over, you can place those blocks in a function. Then just use one run function block wherever you need it in your program.
- Make sure that you log into BlocklyProp, with the BlocklyProp client running, and your board connected and powered on.
- Make a new project using the blocks shown above, and run it.
- When the Terminal opens, click in it and enter your age. You should see something similar to what’s below in your Terminal:
Try This
- Let’s add a new twist, and a new function, that will calculate in how many years the user will turn 100.
- Save the above project, then save it again under a new name.
- Duplicate the entire printAge function, and rename it oldAge.
- At the end of the original printAge function, set a new variable named countdown, and make it equal to 100 minus yourAge.
- Update the oldAge function blocks to use the text and the countdown variable as shown below.
- Add a run function block for oldAge at the end of the main program.
- Save and run the program. When will you turn 100?
Did you Know?
Blockly Variables are Global. Did you notice that the variable item countdown was defined right inside the run function “printAge” block? That did not prevent it from being used inside the oldAge function. In BlocklyProp, all variables are available for use by any other part of the program. This is not always the case in some programming languages, as you might learn if you study C.
Your Turn
- Add a new function that figures out what year the participant was born, and have that print right after printing the age.
- Add a new function that figures out what year the participant will turn 100, and have that print last.