Write down three things you have done today that require many steps but are understood by others when you say a single phrase.
For example: Washed my hair,.
A function is a section of code that can be called to action at anytime during your code. Functions are extremely powerful and allow us to break code down into manageable tasks.
The first reason is reusability. Once a function is defined, it can be used over and over and over again. You can invoke the same function many times in your program, which saves you work.
The advantages of using functions are:
Avoid repetition of codes.
Increases program readability.
Divide a complex problem into simpler ones.
Reduces chances of error.
Modifying a program becomes easier by using function.
Loops will repeat the code inside them for the number of times you ask. Functions run the code inside them only once, but their power is that they can allow you to reuse code anywhere you want.
looped code on the left and the function code below - which would you rather edit?
Both of these examples do the same thing. The difference is when you use functions, you only need to edit things once. If you want to change coordinates, for example, or an animal you are spawning, you just make one change! Without functions, you would need to make five changes. This makes testing and debugging a lot easier.
Grouping frequently used instructions into a function makes your code more efficient but also makes it easier to understand. Functions help you organize your code so that it fits the problem you are coding for. A function is usually given a name that describes the task it will perform when called, making your code easier to read. You are able to divide up problems into smaller, more manageable pieces.
Let’s suppose you want to make code that drives a car. Using functions, you would make one function for each part of driving. You can think about your overall goal and use functions to help you plan. To drive, you need to turn on the car, sit, stop, open the door, and do various other things like this. Each of these would be a function.