Writing a Python function
Assume that we are interested in writing a Python function for equation (1).
After launching Spyder, click File, then New File. We write the following two lines, as shown in the left panel. The keyword def
is for function,fv_f
is the function name, and the three values of pv
, r
, and n
in the pair of parentheses are input variables.
The colon (:
) indicates the function hasn't finished yet. After we hit the Enter key, the next line will be automatically indented.
After we enter return pv*(1+r)**n
and hit the Enter key twice, this simple program is completed. Obviously, for the second line, **
represents a power function.
Assume that we save it under c:/temp/temp.py
:
To run or debug the program, click the arrow key under Run on the menu bar; see the preceding top-right image. The compiling result is shown by the bottom image right (the second image on top right). Now, we can use this function easily by calling it with three input values:
>>>fv_f(100,0.1,2) 121.00000000000001 >>>fv_f(100,0.02,20) 148.59473959783548
If some comments are added by explaining the meanings of input variables, the formula used, plus a few examples, it will be extremely helpful for other users or programmers. Check the following program with comments:
def pv_f(fv,r,n): """Objective: estimate present value fv formula : pv=------------- (1+r)^n fv: fture value r : discount periodic rate n : number of periods Example #1 >>>pv_f(100,0.1,1) 90.9090909090909 Example #2: >>>pv_f(r=0.1,fv=100,n=1) 90.9090909090909 """ return fv/(1+r)**n
The comments or explanations are included in a pair of three double quotation marks ("""
and """
). The indentation within a comment is not consequential. When compiling, the underlying software will ignore all comments. The beauty of those comments is that we can use help(pv_f)
to see them, as illustrated here:
In Chapter 2, Introduction to Python Modules, we will show how to upload a financial calculator written in Python, and in Chapter 3, Time Value of Money, we will explain how to generate such a financial calculator.