Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Special Funding Scheme for Innovation in Virtual Education in Business, CUHK

Learning Financial Analysis with Python from Scratch

Module 5 Defining Functions


*We will use Colab for illustration in this note, while most of them work in Jupyter as well.

5.1 Function
A function is a group of statements that are used for later execution on a specific task.
 The name of a function tells us what the group of statements is going to accomplish.
 Thus, users only need to memorize the name of the function, but not the whole group of
statements.
 The main reason for using functions is that it saves the programmer’s time in repeatedly
writing the same group of statements.
 Programmers can then concentrate on constructing high-level building blocks.
 Another reason is that it is easier to check the error in a program if the whole program is
divided into different sub-parts.

5.2 Def statement


Def statement helps us to create a function that can be used throughout the program.
 The following is an example:
1. Q16
2. return b * h / 2
3. triangle(2,8)
 A function is created starting with a keyword def, followed by the function name (triangle).
 A parenthesis (b,h) is used to state the list of parameters that are used for the function.
 The initial information that we need to input for a function is called parameters.
 The beginning of a group of statements is started after a colon :.
 The body of the function is the group of statements inside a function, which has to be
indented.
 The return statement (return b * h / 2) is used to send the function’s result back to the main
program after the function completes the execution.
 After creating a function, you can then call the function name and input the required
parameters to perform the specific task that you want (triangle(2,8)).

PHU Jacqueline & Dr. Edwin MOK 1


5.3 Main function
One of the good practices in programming is to separate interaction among different tasks.
 The principal program is put into the main function, while the coding of other tasks (i.e.,
calculation and input/output) is put inside different functions.
 One of the advantages of this practice is that the creation of a general-purpose function
(building block) allows us to use them more easily in other programs.
1. def FV (pv, n, r):
2. pv, n, r = float(pv), float(n), float(r)
3. return int(pv*(1+r/100)**n)
4. Q17
5. input1 = input('How much would you like to invest today? ')
6. input2 = input('How long would you like to invest (in years)? ')
7. input3 = input('What is the annual percentage return?' )
8. future = FV(input1, input2, input3)
9. print('You will have',future,'after',input2,'years')
10. main()

5.4 Local vs. global


Parameters that are created inside a function cannot be used outside the body of the function.
 Even if a new value is assigned to a variable that exists outside the function, the variable will
keep its original when it is called outside the function.
 New value can only be used inside the body of the function.
 We call variables that are assigned inside the function local variables.
 Variables that are created or assigned outside a function are called global variables.
 What would be your guess for the two outputs?
1. x = 100
2. def test(y):
3. x=2*y
4. return x
5. Q18
6. print(x)

PHU Jacqueline & Dr. Edwin MOK 2


5.5 Raise statement
Raise statement can stop the running of the program and display an error or exception to a user.
 It is useful when the input is not valid.
 Replace the line since line 8 in 5.3 with the following codes:
8. checkinput(input1,input2,input3)
9. future = FV(input1, input2, input3)
10. print('You will have',future,'after',input2,'years')
11. Q19
12. if float(input1) < 0:
13. raise RuntimeError('Investment cannot be a negative number.')
14. if float(input2) < 0:
15. raise RuntimeError('Investment period cannot be a negative number.')
16. if float(input3) < 0:
17. raise RuntimeError('Expected return cannot be a negative number.')
18. Q20

5.6 Exercises
1. You receive a secret code “.gnitseretni si esruoc ehT” from Edwin. Design a function to decrypt
this message and name the function as decrypt.

2. Design a function to encrypt a message based on the logic of the above secret code. If you want
to send “Yes, it is interesting.”, what would be the encrypted message that you send back to
Edwin? Hints: would your answer the same as the previous one?

3. Without defining x outside the body of a function, design a function that assigns a value of 5 to x,
using the global keyword.

4. Design a program to ask users to input their gender (M for male and F for female). Design a
function to raise RuntimeError if their input is not valid.

End of Module 5

PHU Jacqueline & Dr. Edwin MOK 3

You might also like