1 of 38

Function and Class

2 of 38

What is function

  • Function is a group of related statements that performs a specific task.
  • Function helps to break our program into smaller and modular chunks.
  • As our program grows larger and larger, functions make it more organized and manageable.
  • Function avoids repetition and makes the code reusable.
  • When should we use function:
    • Some codes are used frequently – don’t repeat yourself.
    • A script is too long and not easy to be viewed.
    • A task has specific and clear mission.

3 of 38

The structure of function

  • Function name: defined by the developer. It can be called at outside of the function in the main script.
  • Parameters: the input values from the function call.
  • Function body: the executed statement of the function.
  • Return value: output the result to the main script.
  • Function call: call the defined function with required parameters.

4 of 38

Without return

Actually, the function return None.

5 of 38

The parameters of the function

  • The parameters of the function is imported from the main script. They need to follow two rules.
    • The order of the parameters are the same as the input items.
    • The number of input items must be the same as the number of parameters.

6 of 38

7 of 38

Keyword argument

  • Keyword argument can make the management of parameters become easily and more understandable.
  • The order is not a matter anymore.

8 of 38

Default argument

  • Default argument can set a default value to a parameter. If the parameter is not assigned by any input value, the default value will be used automatically.

The default arguments need to

be placed after the non-default

arguments

9 of 38

Exercise

  • Today, we received a report from biotech company. They gave us two list of genes with their expression values. One is from normal persons and the other is from Covid patients. We want to calculate the average expression value for each of these two datasets. How could we do that? (please use a function to calculate average for avoiding repeating codes.)

Control

Gene ID

Expression

G1021

1102

G1031

3102

G1032

403

G0143

423

G3923

119

G1203

3952

Covid

Gene ID

Expression

G1021

102

G1031

3121

G1032

3403

G0143

398

G3923

134

G1203

4005

10 of 38

Using function

11 of 38

*args, **kwargs

  • Sometimes, if we want to pack a lot of parameters into a function, it may generate a long list of parameter names which is difficult to be viewed. *args, **kwargs are two approaches to pack the parameters to be a tuple or dict for the importation.
  • Because *args uses tuple for packing the parameters, the conversion from tuple to list is required.

12 of 38

tuple

13 of 38

Use for loop to rewrite the script

14 of 38

Shortages of using *args

  • Although *args is very handy, it may also cause some errors if we do not pay attention on the details.
    • The index of *args – since we use *args for pack the input parameters, the elements of the *args usually are many. It would be easy to mess up the elements.
    • Missing input parameters – since the parameters are many, it would be easy to miss some inputs.

15 of 38

**kwargs as a dict

dict

16 of 38

Exercise

  • Please get outputs of these 3 lists of numbers via the following equation. (please use function with *args or **kwargs)

List name

Biochemistry

70

87

67

99

94

84

67

Programming

90

93

89

83

90

93

81

Anatomy

87

67

72

79

90

76

88

17 of 38

18 of 38

Local variables and global variables

  • Local variables are only valid or existed in a function. If we jump to another function, local variables will not be recognized anymore.
  • Global variables are valid in the whole script. No matter which function we are, global variables always be recognized.

a = 1

a = 1

a = 1

b = 2

b = None

b = None

19 of 38

a is a global variable

b is a local variable

How can we make b recognizable outside of the function?

Using assigned parameters to functions and

return from the functions can assist the transfer

of variables.

20 of 38

Called by value and called by reference

  • A variable occupies a memory space (address) of the computer. A memory space can store different values (people).
  • Called by value – the variable was changed or called based on values. If we only call a value without corresponding address, the output may either wrong or not be found at all.
  • In the call by value method, there is no modification in the original value.
  • Called by reference – when the variable was changed or called, the whole address was used.
  • In the call by reference method, there is a modification in the original value.
  • For checking the memory address, we can use id().

21 of 38

3

“ttt”

345.21

None

False

“OK”

Input += 3

a

s

value

detect

ans

The original a is not changed.

Called

by

value

3

“ttt”

345.21

None

False

“OK”

a = [

]

index

Variable name

0

1

2

3

4

5

def function(input)

def function(input)

Input[0] += 3

The original a is changed.

Called

by

reference

Normally, the variable with single value belongs to called by value. List, dict and tuple belong to called by reference.

But if the whole list, dict or tuple are reassigned. It also belongs to called by value

22 of 38

Called by value

Called by value: use return to replace the original value

Called by reference: without using return

list, tuple and dict all fit this type.

Special case:

The whole list was reassigned

return is needed

in this case

23 of 38

Exercise

  • The hospital received 3 patients yesterday. Today, the 1st patient recovered and left the hospital, and we received another two patients. Could you please updated the list of patients? (please use a function for the update.)

Name

Age

Room number

Kevin

34

301

James

67

302

Ann

15

303

Name

Age

Room number

Jeremy

40

301

Kevin

33

304

original

new patients

24 of 38

25 of 38

Main function

  • Main function is the point where python starts to execute the script.
  • Without a main function, python will still execute the script from the top to bottom. It will be fine if we only run the script. But if we want to import a function of the script as a package to another script. Without a main function, it will waste the memory to run the main function.
  • The basic format of main function is:

__ indicate the variable is predefined by python. __name__ will store the name of function which are executed currently. Without importing to other script, __name__ will be __main__ when the script starts to run.

26 of 38

1

2

3

__name__ = “get_sum”

4

__name__ = “__main__”

27 of 38

Exercise

Rewrite the script with a main function

28 of 38

29 of 38

30 of 38

Class

  • Class is the way of python for managing object-oriented (物件導向) mission.
  • A object-oriented programming normally is composed of the following items:
    • Class
    • Object
    • Attribute
    • Constructor
    • Method

class

constructor

object

method

attribute

31 of 38

32 of 38

Class

  • We usually name the class by the following rule:
    • The first alphabet of each word is capitalized.
    • No space and underline.
    • End with a :

    • Examples

33 of 38

Object

  • Object is the item which created by defined class.
  • The syntax of object is

  • Examples

  • We can use isinstance to check the relationship between object and class.

34 of 38

Attribute

  • Attributes are used for storing the information of a object.
  • The syntax is:

  • Examples:

35 of 38

Constructor

  • Using constructor can make the script easy to handle and more understandable.

36 of 38

Constructor - self

  • When we generate constructor, self is required.
  • self represents the object itself. Based on it the constructor will know that the attributes need to be assigned to which object.

Already know from the object

self does not need to be

assigned

37 of 38

Method

  • Method is similar as function. It is used for managing object or input data.
  • The difference between method and function is self is required for method.

required

38 of 38

Exercise

  • A hospital wants to create a system for managing the wards. The information they need is room number, patient name, doctor name, gender and age. The hospital has normal and ICU ward. Please make the system can add, remove, and transfer (from normal to ICU or from ICU to normal) the patients’ information.

How to debug – use print wisely

Script can be downloaded from https://drive.google.com/file/d/1coz2CM_fPYnaORWLdtlrwRFe6X3-nIJR/view?usp=sharing