Custom Functions Workout
- 02:13
Practise creating custom functions in Python.
Downloads
No associated resources to download.
Glossary
custom functions Future Value PythonTranscript
Let's get some practice with custom functions by recreating the Excel formula shown here that calculates future value. And there are a couple of notes right here first of all that your formula is going to be investment times 1 plus your growth rate to the power of however many years. And remember, in Python, you don't use that little carrot to do exponents. You do the double asterisk and that's going to raise your number to the power of, in this case, three years. Next, if you want to have multiple arguments in your function, follow the format right here. First, your function, and then in parentheses you have your first argument and then just a comma, and then your second argument and a comma and your third argument. And in that way, you can have multiple arguments for each of your variables here, your investment, your growth rate, and the number of years. And then third, if you wanna be clean and you want to round your output, just use the round function. The first argument and the round function is the number that you want to round. And then the second argument is gonna be the number of decimal places.
Our job here is to create a custom function that calculates future value, given a few different investment metrics. I'm gonna start with the def keyword to tell Python. I'm defining a new custom function, and I'm going to name this future value in my parentheses. I want to have arguments for my investment, my growth rate, and the number of years that that investment's going to be growing. So now I have three arguments for my three variables. Then I'm gonna put a colon and I'm gonna tell Python what to do once it's given those numbers. And here I'm going to tell it to print the rounded value.
And I'm just going to copy the formula that was given in the exercise. So I have my investment multiplied by one plus my growth rate to the power of the number of years. And to make sure that's working correctly. I can give future value the numbers from the exercise and check my answer. So I have an investment of 100, a growth rate of 10%, and three years that we're gonna grow that when I execute it. I'm going to get 133.