The definition of a function is a set of operations done to an input to return an output. But in code, a function is a set of code which doesn't always require an input and doesn't always give an output. We use functions when we want to repeat some code in different parts of the program. For example, let's say you have a robot which you want it to walk. Instead of saying complex steps over and over again like "lift your foot" and "put it forward", we can just store those steps in a function and just use that function when we want to. The usage of a function is a call and the part with all the code for how the function operates is called the definition. Here is an example of the call and definition of a function.
Sometimes, in a function, you might want to give an input. Those are parameters. If you look at the example above, our parameter was x and y. We can have as many parameters as we want.
Whenever you have a parameter, we always have to tell what those parameters mean. Those are called arguments. In the function above, the x was 5 and the y was 7. If you want to call out the same function again, you can do it with different arguments. So basically, you can change what the parameters will mean each time you call out a function. Here is an example below.
As you can see above, I called out the function 3 times and all 3 times, the arguments were different. Which made each output different.
Sometimes, in a function, you might want to store the output the function gives for later use. In our previous function, we had an output but didn't store it anywhere. You can do that with a return statement and store that return with a variable. Here's an example below.
Make a program that involves using 2 parameters and adding them inside the function. The function should return the sum of the 2 parameters and there should be a line outside the function that prints the return value.
Copyright © 2024 PieceOfAPie - All Rights Reserved.
Powered by GoDaddy
We use cookies to analyze website traffic and optimize your website experience. By accepting our use of cookies, your data will be aggregated with all other user data.