Remember all the times we used a ‘block’ that performs certain actions. Whether it was to perform basic mathematics, run logics and loops, or even create and work on lists, we invoked functions.
A function is a group of program statements that is created to perform a certain task. It has a name and every time that name is used the function is invoked.
All the blocks in blockly are in sense predefined functions. Remember when we created a code to find the minimum and maximum in a list( if you don’t remember, it’s okay. You can always visit previous lessons to revise). What we did there was essentially create a function. The following block will also perform the same task.
Now compare it to the code we built earlier. It’s much smaller, right? Now imagine you have to write code to create 5 different lists and perform different actions( finding the maximum, finding the minimum, finding the average, etc). If we have to create a complete code for each action, the final code will become very large. Instead, we can create one function to perform these task and use it multiple times without having to repeat the whole process.
After all, what’s the difference between a code with 1000 lines and one with 100, correct? Well, the answer is massive. The larger the code, the more chances of error exist.
But in this course, we will not delve deeper into functions except their basics. Let us further understand them with the following code.
Let’s say you have to create multiple lists with different numbers of elements and different ranges of values. But if you write separate code for each list, the code will become heavy. Instead, we can create a function and invoke it for different lists.
We have created this function. It is similar to what you have created in the lesson on lists. Here X= the number of elements in the list.
Y= range of random numbers ( eg is y=10 then random numbers will be generated from within 1-10).
To invoke this function we will use this block:-
Simple enough, correct? All you need to do is the value of x and y for different lists and voila, you have your results.