In the previous lesson, we talked about how functions can take inputs to allow them to do customized tasks. But, not only can functions take inputs, they can also send information back (return output) to other parts of the code. A good example of this is when we have a function that does some calculations for us, and we want to get the results of those calculations.
Perhaps instead of printing the name and birth year of people, we’d rather know how old the person will be on their birthday this year. Using the information we already have from our previous lesson, this calculation is pretty simple – we just subtract the birth year from the current year (2015 as of this writing) and we’ll get the age they will be turning this year.
To create a new function to do this, we can still pass in the “year” parameter for the person’s birth year (like we did in the previous project) but, instead of printing the information, we do our age calculation and store the resulting value in a new variable called “age”.
This is what the function would look like:
Note: This is the reason we decided to keep the “year” parameter as a number instead of a string in the previous lesson -- so that we could use it to perform this calculation.
Now, to send the information we’ve calculated back to the main program, we end the function with a return statement that contains the information we’re sending back (in this case, we’re sending the information contained in the variable, “age”):
The value of “age” would then be returned to where the function was called and that value could be stored in another variable, printed or used however it is needed.
For example, we could call this function for Bob and Susie like we did in the last project, but this time, we could get their age as well, store it in a variable and then print it out:
Here is what the entire program would look like:
There's only one more function lesson you need to be familiar with before jumping back into the project. We promise...just one more! Here you go: Using Functions & Modules.