You are on page 1of 85

Chapter 7A.

Functions
ENGG 1330 Computer Programming I
Dr. Chui Chun Kit and Dr. Dirk Schnieders

Department of Computer Science, The University of Hong Kong

Slides prepared by - Dr. Chui Chun Kit (http://www.cs.hku.hk/~ckchui/) and Dr. Dirk Schnieders for students in ENGG1330. For other uses, please email : ckchui@cs.hku.hk
We are going to learn…
Divide and Conquer problem solving strategy.
Syntax of function.
Defining a function.
Calling a function.

Local vs global variables


Return value(s)
Default, positional and keyword arguments

2
Section 7A.1

Divide and conquer

Slides prepared by - Dr. Chui Chun Kit (http://www.cs.hku.hk/~ckchui/) and Dr. Dirk Schnieders for students in ENGG1330. For other uses, please email : ckchui@cs.hku.hk
Divide and conquer
A good way to design a program is to break down the task to be
accomplished into a few sub-tasks.
Each sub-task can be further decomposed into smaller sub-tasks, and
this process is repeated until all sub-tasks are small enough that
their implementations become manageable.

A powerful problem solving skill in business, management,


engineering, and computer programming.

4
Divide and conquer
BMI Category
<18.5 Underweight
Within 18.5 and 22.9 Normal
>22.9 Overweight

Please write a program that reads in the weight (in kg)


and height (in meter) of a user, and calculates the Body
Mass Index (BMI) of that user, and finally generates
output reporting the category of the user based on
his/her BMI.
5
Divide and conquer
Read in height and
weight of user.
We can tackle the problem by
dividing our program into 3
Calculate the BMI
sub-tasks.
We will treat each part as a
smaller problem and tackle
(conquer) the smaller
Output the category problems one by one.
based on the BMI
Flowchart 6
Divide and conquer
Read in height and Input: nothing
weight of user.

Obtain user input height


Calculate the BMI (in m) and weight (in kg)
in float type

Output the category Output: height (in m) and weight (in kg)
based on the BMI
Flowchart
7
Divide and conquer
Read in height and Input: height (in m) and weight (in kg)
weight of user.

weight (in kg)


Calculate the BMI BMI =
height(in m)2

Output the category


Output: BMI
based on the BMI
Flowchart 8
BMI Category
Divide and conquer <18.5
Within 18.5 and 22.9
Underweight
Normal
Input: BMI
>22.9 Overweight
Read in height and
weight of user.
Yes
Print:
BMI<18.5 ?
Underweight
No
Calculate the BMI Yes
Print:
18.5 <= BMI <=22.9 ?
Normal
No
Yes
Print:
BMI>22.9 ?
Output the category Overweight

based on the BMI


Flowchart 9
Output: Nothing
Divide and conquer
Before we elaborate on the sub-tasks, we identify the
1. Input(s) – Translates to function arguments / parameters

2. The objective of the sub-task (But not the process of how the task is done).

3. Output(s) – Translates to function return statement

Input: height and weight Calculate the BMI Output: BMI

Problem Solving Technique:


At the time you realize a sub-task, you only need to think of
the input and output of the sub-task, without worrying
about the logic inside the sub-task. 10
Section 7A.2

Define function &


call function

Slides prepared by - Dr. Chui Chun Kit (http://www.cs.hku.hk/~ckchui/) and Dr. Dirk Schnieders for students in ENGG1330. For other uses, please email : ckchui@cs.hku.hk
Defining a function in Python
Input arguments / parameters
Keyword to
define a def function_name (arg1, arg2, … , argN):
function statement_1
statement_2

Return
statement return statement

When defining a function, we can define…


Function name (or we call it the identifier of the function, can use any valid
identifier name).
Input arguments – Can be none (an empty bracket) or many (separate by comma)

Return statement (optional) for returning value(s) back to function caller.


Usually returning the calculated / processed data back to the function caller.
12
The calculate_bmi() function
Input: height (in m) and weight (in kg) Input: height (in m) and weight (in kg)

1 def calculate_bmi (height, weight):


bmi = weight / (height * height)
weight (in kg) return bmi
BMI =
height(in m)2

Output: BMI

13
The calculate_bmi() function
Input: height (in m) and weight (in kg) Input: height (in m) and weight (in kg)

def calculate_bmi (height, weight):


bmi = weight / (height * height)
weight (in kg) 2 return bmi
BMI =
height(in m)2
Output: BMI

Important concept:
Note that function output refers to the value(s) giving
Output: BMI back to the function caller but not a print() statement.
i.e., After processing the height and weight, the
function caller should expect to receive a bmi value for
further processing.
14
The calculate_bmi() function
Input: height (in m) and weight (in kg) Input: height (in m) and weight (in kg)

def calculate_bmi (height, weight):


3 bmi = weight / (height * height)
weight (in kg) return bmi
BMI =
height(in m)2
Output: BMI

Okay! I have finished defining the


Output: BMI calculate_bmi() function. But when
I execute this program in Python,
there is no output, why?
15
Calling the calculate_bmi() function
def calculate_bmi (height, weight): The calculated bmi is: 22.857142857142858
bmi = weight / (height * height)
return bmi

bmi = calculate_bmi(1.75, 70)


print("The BMI value is:",bmi)

The following line


bmi = calculate_bmi(1.75, 70)
called the function with height as 1.75, weight as 70,
and the function returns 22.857142857142858 as result.
What actually happened to the flow of program?

16
Calling the calculate_bmi() function
def calculate_bmi (height, weight):
bmi = weight / (height * height)
return bmi

bmi = calculate_bmi(1.75, 70)


print("The BMI value is:",bmi) Define the calculate_bmi() function

Python note the calculate_bmi()


function is defined.

Python will NOT execute the


function as it is not called yet.

17
Calling the calculate_bmi() function
def calculate_bmi (height, weight):
bmi = weight / (height * height)
return bmi

bmi = calculate_bmi(1.75, 70)


print("The BMI value is:",bmi)

Call the calculate_bmi() function

When a function call is


encountered, the current statement
execution is suspended.

18
Calling the calculate_bmi() function
def calculate_bmi (height, weight):
bmi = weight / (height * height)
return bmi

bmi = calculate_bmi(1.75, 70)


print("The BMI value is:",bmi)
Execute the calculate_bmi() function

The calculate_bmi() function is executed


with height = 1.75, weight = 70.

The function calculates


bmi = 22.59814049586..

The function return 22.59814049586…


19
Calling the calculate_bmi() function
def calculate_bmi (height, weight):
bmi = weight / (height * height) bmi = calculate_bmi(1.75, 70)
return bmi

bmi = calculate_bmi(1.75, 70) bmi = 22.857142857142858


print("The BMI value is:",bmi)

Important concept:
After a function is executed, the program goes back to the
statement where the function is called.
The statement is simplified as the function resolves to its
returned value.
20
Calling the calculate_bmi() function
def calculate_bmi (height, weight): The BMI value is: 22.857142857142858
bmi = weight / (height * height)
return bmi

bmi = calculate_bmi(1.75, 70)


print("The BMI value is:",bmi)

Questions.
Are there other ways to call the calculate_bmi() function?
Is the bmi variable inside calculate_bmi() function the
same as the bmi variable outside the calculate_bmi()
function?

21
Common practices: The main() function
In python, it is a common convention to define a function called main()
which gets called when the program start.
This main() function then goes on to call other function as needed.
def calculate_bmi (height, weight): Execution starts at the main() function
bmi = weight / (height * height) With the main() in this position, the first
return bmi function to execute in the program will be the
main() function.
def main():
height = float(input("Height(in m):")) main() function will continue to call other
weight = float(input("Weight(in kg):")) functions.
bmi = calculate_bmi(height, weight)
print("The BMI value is:",bmi) Height(in m): 1.75
Weight(in kg): 70
main() The BMI value is: 22.857142857142858
22
Section 7A.3

Local vs global variables

Slides prepared by - Dr. Chui Chun Kit (http://www.cs.hku.hk/~ckchui/) and Dr. Dirk Schnieders for students in ENGG1330. For other uses, please email : ckchui@cs.hku.hk
Local variables
Variable declared within a function, including input arguments, are
private or local to that particular function, i.e., no other function can
have direct access to them.

Local variables in a function come into existence only when the function
is called, and disappear when the function is ended / returned.

Local variables declared within the same function must have unique
names, whereas local variables of different functions may use the
same name.

24
Height(in m): 1.75

Example 1 Weight(in kg): 70

def calculate_bmi (height, weight):


bmi = weight / (height * height)
return bmi

def main():
height = float(input("Height(in m):"))
weight = float(input("Weight(in kg):"))
bmi = calculate_bmi(height, weight)
print("The BMI value is:",bmi)

main()

Local variables in main()


height weight bmi
1.75 70 ?
25
Height(in m): 1.75

Example 1 Weight(in kg): 70


The BMI value is: 22.857142857142858
def calculate_bmi (height, weight):
bmi = weight / (height * height)
return bmi Important concept
Note that the height/
def main(): weight/ bmi variables in
height = float(input("Height(in m):"))
weight = float(input("Weight(in kg):"))
main() and the height/
bmi = calculate_bmi(height, weight) weight/ bmi variables in
print("The BMI value is:",bmi) calculate_bmi(), although
they have the same names,
main()
they are different variables.

Local variables in main() Local variables in calculate_bmi()


height weight bmi height weight bmi
1.75 70 22.857142857… 1.75 70 22.857142857…
26
Example 2
def calculate_bmi (h, w):
bmi_val = w / (h * h) Question:
return bmi_val Since variables are local to
functions, will the program still
def main():
height = float(input("Height(in m):")) works if I update the name of the
weight = float(input("Weight(in kg):")) variables in the calculate_bmi()
bmi = calculate_bmi(height, weight) function as follows?
print("The BMI value is:",bmi)

main()
print("End of program")

It still works !
To understand it you need to be very clear about
scope of variables. Let’s illustrate what’s happen to
the variables when the program is being executed 
27
Example 2
def calculate_bmi (h, w):
bmi_val = w / (h * h) Execute the main() function
return bmi_val

def main(): Python noted the definition of


height = float(input("Height(in m):")) calculate_bmi() and main()
weight = float(input("Weight(in kg):")) function.
bmi = calculate_bmi(height, weight)
print("The BMI value is:",bmi)
It then encounter the function call
main() in the 2nd last line main().
print("End of program")
Therefore Python suspend the
current execution and executes the
main() function.

28
Example 2
def calculate_bmi (h, w):
bmi_val = w / (h * h) Local variables in the main() function
return bmi_val

def main(): With the two lines regarding


height = float(input("Height(in m):")) height and weight input,
weight = float(input("Weight(in kg):")) Python will define these two
bmi = calculate_bmi(height, weight)
print("The BMI value is:",bmi) variables as LOCAL to the main()
function.
main()
print("End of program") Say user input 1.75 and 70
Local variables in main() correspondingly to the two
variables.
height weight
1.75 70
29
Height(in m): 1.75

Example 2 Weight(in kg): 70

def calculate_bmi (h, w):


bmi_val = w / (h * h) The statement that calls calculate_bmi()
return bmi_val
This statement has an assignment
def main():
height = float(input("Height(in m):")) operator =, which assigns the value
weight = float(input("Weight(in kg):")) on the R.H.S. to the variable in the
bmi = calculate_bmi(height, weight)
L.H.S.
print("The BMI value is:",bmi)
Therefore, there is a variable bmi,
main()
print("End of program") which is LOCAL to main() created.
Local variables in main() Since the R.H.S. of the assignment
operator = is a function call, Python
height weight bmi will suspend the execution in main()
1.75 70 ? function and execute the function
calculate_bmi(). 30
Height(in m): 1.75

Example 2 Weight(in kg): 70

def calculate_bmi (h, w):


bmi_val = w / (h * h) Local variables in calculate_bmi()
return bmi_val
The input arguments in function are
def main():
height = float(input("Height(in m):")) also LOCAL to that function. i.e., h,
weight = float(input("Weight(in kg):")) w are local to calculate_bmi().
bmi = calculate_bmi(height, weight)
print("The BMI value is:",bmi) bmi_val is also a LOCAL variable
in calculate_bmi().
main()
print("End of program")

Local variables in main() Local variables in calculate_bmi()


height weight bmi h w bmi_val
1.75 70 ? 1.75 70 22.857142857…
31
Height(in m): 1.75

Example 2 Weight(in kg): 70

def calculate_bmi (h, w): Return of calculate_bmi()


bmi_val = w / (h * h)
return bmi_val calculate_bmi() return bmi_val,
simplifying the statement in main()
def main():
height = float(input("Height(in m):")) function to be:
weight = float(input("Weight(in kg):")) bmi = 22.857142857…
bmi = calculate_bmi(height, weight) Then the calculate_bmi() function
print("The BMI value is:",bmi)
finished its execution. All its local
main() variables are destroyed.
print("End of program") 2
Local variables in main() 1 Local variables in calculate_bmi()
height weight bmi h w bmi_val
1.75 70 22.857142857… 1.75 70 22.857142857…
32
Height(in m): 1.75

Example 2 Weight(in kg): 70


The BMI value is: 22.857142857142858
def calculate_bmi (h, w):
bmi_val = w / (h * h) main() function also finishes
return bmi_val
The last statement of main() function
def main():
height = float(input("Height(in m):")) prints the value of its local variable bmi.
weight = float(input("Weight(in kg):"))
bmi = calculate_bmi(height, weight) In fact, main() function is a function
print("The BMI value is:",bmi) without return statement. After its
execution of last statement the function
main()
print("End of program") ends and returns nothing (in fact a None
is returned). Python will resume its
Local variables in main() execution to the 2nd last line.
height weight bmi Similarly, with the end of the main()
1.75 70 22.857142857… function, the local variables in
main() will also be destroyed. 33
Height(in m): 1.75

Example 2 Weight(in kg): 70


The BMI value is: 22.857142857142858
End of program
def calculate_bmi (h, w):
bmi_val = w / (h * h)
return bmi_val

def main():
height = float(input("Height(in m):"))
weight = float(input("Weight(in kg):"))
bmi = calculate_bmi(height, weight) Execute the last line of code
print("The BMI value is:",bmi)
Finally Python reaches the last line
main() of code and prints the “End of
print("End of program")
program”, and the program ends.

34
Example 3
def calculate_bmi (h, w):
bmi = w / (h * h)
Doubt:
def main():
height = float(input("Height(in m):")) Can I update the bmi variable in
weight = float(input("Weight(in kg):")) calculate_bmi() function, and
calculate_bmi(height, weight) print the bmi variable in main()
print("The BMI value is:",bmi)
function?
main()
print("End of program")

Can you explain why the above code does not work?
To understand it you need to be very clear about
scope of variables. Let’s illustrate what’s happen to
the variables when the program is being executed 
35
Example 3
def calculate_bmi (h, w):
Height(in m):1.75
bmi = w / (h * h) Weight(in kg):70
Traceback (most recent call last):
def main():
height = float(input("Height(in m):"))

weight = float(input("Weight(in kg):")) NameError: name 'bmi' is not defined
calculate_bmi(height, weight)
print("The BMI value is:",bmi) bmi variable is not defined in main()
main() Note that the bmi variable is local in
print("End of program")
calculate_bmi(), bmi is not defined in
main().
Local variables in main() Local variables in calculate_bmi()
height weight h w bmi
1.75 70 1.75 70 22.857142857… 36
Example 4
def calculate_bmi (h, w):
Doubt: Can I define bmi=0 in
bmi = w / (h * h) main() function, update bmi
def main(): in calculate_bmi(), and print
bmi=0 the updated bmi value in
height = float(input("Height(in m):"))
weight = float(input("Weight(in kg):")) main()?
calculate_bmi(height, weight)
print("The BMI value is:",bmi)

main()
print("End of program")

Does not work either!


Because the bmi variable in main() is different
from the bmi variable in calculate_bmi()!
37
Example 4
def calculate_bmi (h, w): Height(in m):1.75
bmi = w / (h * h)
Weight(in kg):70
def main(): The BMI value is: 0
bmi=0 End of program
height = float(input("Height(in m):"))
weight = float(input("Weight(in kg):"))
calculate_bmi(height, weight)
print("The BMI value is:",bmi)

main()
print("End of program")

Local variables in main() Local variables in calculate_bmi()


height weight bmi h w bmi
1.75 70 0 1.75 70 22.857142857…
38
Example 5 Doubt: Can I define bmi=0 in
main() function, pass bmi as
def calculate_bmi (height, weight, bmi):
bmi = weight / (height * height)
3rd argument in calculate_bmi()
and update bmi in
def main():
bmi=0 calculate_bmi() , and print
height = float(input("Height(in m):")) the updated bmi value in
weight = float(input("Weight(in kg):"))
calculate_bmi(height, weight, bmi) main()?
print("The BMI value is:",bmi)

main()
print("End of program")

Does not work either!


Because the bmi variable in main() is different
from the bmi variable in calculate_bmi()!
39
Example 5
def calculate_bmi (height, weight, bmi): Height(in m):1.75
bmi = weight / (height * height) Weight(in kg):70
The BMI value is: 0
def main():
bmi=0 End of program
height = float(input("Height(in m):"))
weight = float(input("Weight(in kg):"))
calculate_bmi(height, weight, bmi)
print("The BMI value is:",bmi)

main()
print("End of program")

Local variables in main() Local variables in calculate_bmi()


height weight bmi height weight bmi
1.75 70 0 1.75 70 22.857142857…
40
Global variables
Variables may also be declared outside all functions.
Such variables are called global variables because they can be accessed by all
functions, i.e., globally accessible.
Global variables remain in existence permanently
Retain their values even after the functions that set them have returned.
The values of global variables can be changed by several functions.

Professional practices:
Although global variable is a quick resort to many new programmers,
we seldom use global variable as it can be modified by many functions
and is very hard to trace.
We will use function return to keep passing the updated variable across
functions 41
Global variables – keyword global
bmi=0 The global keyword.
def calculate_bmi (height=1.75, weight=70):
global bmi If we need to update the
bmi = weight / (height * height)
value of the variable, if it is
def main(): global variable, we need to
height = float(input("Height(in m):"))
weight = float(input("Weight(in kg):")) use the keyword global to
calculate_bmi(height, weight) tell Python that it is a global
print("The BMI value is:",bmi)
variable. Otherwise, Python
main() will treat it as a new local
Height(in m): 1.75
variable.
Weight(in kg): 70
The BMI value is: 22.857142857142858

42
Example 5
n = 10

def func1():
n = 100

def func2():
print(n)
Doubt: Will the
func1()
program prints out 10
func2()
or 100?

43
Example 5
n = 10
Global variable n
def func1():
n = 100
Since n is defined outside any
def func2(): functions, n is a global variable.
print(n)

func1()
func2()

Global variable
n
10
44
Example 5
n = 10
Execute func1()
def func1():
n = 100
With n = 100, it means that we define a new local
def func2(): variable n in func1(), and assign value of 100 to it.
print(n)

func1()
func2()

Global variable Local variable in func1()


n n
10 100
45
Example 5
n = 10 10
Execute func2()
def func1():
n = 100
With print(n), since there is no local
def func2(): variable n in func2(), Python will
print(n) regard n as the global variable n
func1()
and prints out value of 10.
func2()

Global variable Local variable in func1()


n n
10 100
46
Example 6
n = 10

def func1():
global n
n = 100

def func2():
Doubt: Will the
print(n)
program prints out 10
func1()
func2()
or 100?

47
Example 6
n = 10
Global variable n
def func1():
global n
Since n is defined outside any functions, n is a global
n = 100
variable.
def func2():
print(n)

func1()
func2()

n
10
48
Example 6 100
n = 10 Execute func1()
def func1(): With global n, Python knows that variable n in func1() is a
global n
n = 100 global variable.

def func2(): n = 100 will update global variable n, but not to define
print(n)
another local variable n in func1().
func1()
func2() Execute func2()

Global variable Although there is no global n statement in func2(),


print(n) will still access the global variable n.
n
100 It is because we only access the value of n, not
defining a new n here. 49
Section 7A.4

Return value(s)

Slides prepared by - Dr. Chui Chun Kit (http://www.cs.hku.hk/~ckchui/) and Dr. Dirk Schnieders for students in ENGG1330. For other uses, please email : ckchui@cs.hku.hk
Return value(s) in function
If a function returns a value then a call to such a function can be used
as an operand in any expression in the program.

def calculate_bmi (height, weight): Important tips


bmi = weight / (height * height) If an immutable object (int, float,
return bmi
str, number, tuple, bool, etc) has
def main(): to be updated in a function, we
height = float(input("Height(in m):")) will use return statement to
weight = float(input("Weight(in kg):")) return the updated value back to
bmi = calculate_bmi(height, weight) the function caller and update
print("The BMI value is:",bmi)
the original variable.
main() We will explain the details in
part B of this chapter.
51
Very useful! Return multiple values
To return multiple values from a function just specify each value
separated by comma (,) after the return keyword.
def getInput():
Input: nothing height=float(input("Height(in m): "))
Read in height and weight=float(input("Weight(in kg): "))
weight of user. return height,weight

Obtain user input def main():


height (in m) and height,weight=getInput()
Calculate the BMI weight (in kg) in print(height, weight)
float type
main()

Output: height (in m) and


Output the category weight (in kg)
based on the BMI
52
Flowchart
Very useful! Return multiple values
When calling a function returning multiple values, the number of variables
on L.H.S. of = operator must be equal to the number of values returned by
the return statement.
def getInput():
Input: nothing height=float(input("Height(in m): "))
Read in height and weight=float(input("Weight(in kg): "))
weight of user. return height,weight

Obtain user input def main():


height (in m) and height,weight = getInput()
Calculate the BMI weight (in kg) in print(height, weight)
float type
main()

Output: height (in m) and Height(in m): 1.75


Output the category weight (in kg) Weight(in kg): 70
based on the BMI 1.75 70.0
53
Flowchart
Functions can return nothing (None)
Input: BMI
def output_category (bmi):
print("Your bmi value is:",bmi)
if (bmi < 18.5):
Yes print("Underweight.")
Print:
BMI<18.5 ? elif(18.5 <= bmi <= 22.5):
Underweight
print("Normal.")
No elif(bmi > 22.5):
print("Overweight.")
Yes
Print:
18.5 <= BMI <=22.9 ?
Normal
def main():
No
height,weight=getInput()
Yes bmi=calculate_bmi(height,weight)
Print:
BMI>22.9 ?
Overweight output_category(bmi)

main()

Output: Nothing 54
Section 7A.5

Default, positional, &


keyword arguments

Slides prepared by - Dr. Chui Chun Kit (http://www.cs.hku.hk/~ckchui/) and Dr. Dirk Schnieders for students in ENGG1330. For other uses, please email : ckchui@cs.hku.hk
Default argument
In Python, we can define function with default parameter values, this
default value will be used when a function is invoked without any argument.
def calculate_bmi (height=1.75, weight=70): Default argument
bmi = weight / (height * height)
The calculate_bmi() function now has default
return bmi value for height and weight input
arguments.
def main():
bmi = calculate_bmi() If user call the calculate_bmi() function without
print("The BMI value is:",bmi) specifying the value of height / weight, the
height = float(input("Height(in m):")) default value will be used.
weight = float(input("Weight(in kg):")) The BMI value is: 22.857142857142858
bmi = calculate_bmi(height, weight) Height(in m): 1.8
print("The BMI value is:",bmi) Weight(in kg): 90
The BMI value is: 27.777777777777775
main()
Default argument
Default arguments are evaluated at definition time, not function run time.
import datetime Import datetime library
def greeting(time=datetime.datetime.now()): The datetime library is useful to obtain and
print(time) process date time.
def main(): Reference
while(True): https://docs.python.org/3.7/library/datetime.html
greeting()
Default argument for time parameter
main()
time is an input argument in greeting()
function.

We set time’s default value as


datetime.datetime.now(), which gives the
current datetime.
57
Default argument
Default arguments are evaluated at definition time, not function run time.
import datetime 2018-10-02 13:51:19.392749
2018-10-02 13:51:19.392749
def greeting(time=datetime.datetime.now()): 2018-10-02 13:51:19.392749
print(time)
2018-10-02 13:51:19.392749
def main():
2018-10-02 13:51:19.392749
while(True): …
greeting()

main()
Important concept:
Please note that the default arguments are evaluated at the time when
the function is defined, therefore this program will not give updated
time but the same time (when the function is defined) is printed.
58
Default argument (None keyword)
Default arguments are evaluated at definition time, not function run time.
import datetime 2018-10-02 14:05:34.003121
1 2018-10-02 14:05:34.003121
def greetingPro(time=None): 2018-10-02 14:05:34.018750
if time==None: 2018-10-02 14:05:34.034381
2 time=datetime.datetime.now() 2018-10-02 14:05:34.034381
print(time)
2018-10-02 14:05:34.050008
def main(): …
while(True):
greetingPro()

main() Good practice:


It will be a good practice to use =None to define the default arguments
and define its default value inside the function.
With the default value set in function body, it is executed during
function runtime. 59
Default argument (None keyword)
def student(name,uid,faculty="Engineering",dpt="Computer Science"):
print("Student",uid,name,"from",faculty,dpt)

def main():
Student 20181111 Kit from Engineering Computer Science
student("Kit",20181111)
Student 20182222 Ben from None CE
student("Ben",20182222,None,"CE")
Student 20183333 Mary from Science Mathematics
student("Mary",20183333,"Science","Mathematics")
main()

def studentPro(name,uid,faculty=None,dpt=None):
if faculty==None:
faculty="Engineering"
if dpt==None:
dpt="Computer Science"
print("Student",uid,name,"from",faculty,dpt)
Student 20181111 Kit from Engineering Computer Science
def main(): Student 20182222 Ben from Engineering CE
studentPro("Kit",20181111) Student 20183333 Mary from Science Mathematics
studentPro("Ben",20182222,None,"CE")
studentPro("Mary",20183333,"Science","Mathematics")
main() 60
Keyword argument
When calling a function, we can also associate the argument name and
value instead of following the order of the arguments.

def calculate_bmi (height, weight):


bmi = weight / (height * height) The BMI value is: 22.857142857142858
return bmi

def main():
bmi = calculate_bmi(weight=70, height=1.75)
print("The BMI value is:",bmi)

main()

61
Mixing positional and keyword arguments
Positional arguments cannot follow keyword arguments
def studentPro(name,uid,faculty=None,dpt=None):
if faculty==None: Error: Positional argument follow
faculty="Engineering"
if dpt==None: keyword argument
dpt="Computer Science"
print("Student",uid,name,"from",faculty,dpt) Keyword arguments following positional
arguments are okay, while positional
def main(): arguments following keyword arguments are
studentPro("Kit",20181111)
studentPro("Ben",20182222,None,"CE")
not okay.
studentPro("Mary",20183333,"Science","Mathematics")

studentPro("Justin",dpt="Actuarial Science", faculty="Science",uid=20184444)

studentPro(name="Kate",20185555,None,None)

main()
62
Section 7A.6

Example

Slides prepared by - Dr. Chui Chun Kit (http://www.cs.hku.hk/~ckchui/) and Dr. Dirk Schnieders for students in ENGG1330. For other uses, please email : ckchui@cs.hku.hk
ENGG1330 Supermarket
Product ID Product Unit price
Displays welcome
0 Chicken 20
message
1 Milk 6.5
2 Chocolate 10
Yes Handle purchase
Purchase?
of one product
No

Handle checkout

Please design and implement


a checkout system for my
supermarket.
65
The purchase() function
Product ID Product Unit price
Displays welcome
0 Chicken 20
message
1 Milk 6.5
2 Chocolate 10
Yes Handle purchase
Purchase? Input: Nothing
of one product
Purchase
No
Display product menu

Handle checkout Ask what is the


product to purchase

Ask the quantity of that product.

Calculate and display


price = unit-price * quantity

Output: The price of the purchase 66


The showMenu() function
Product ID Product Unit price
0 Chicken 20
1 Milk 6.5
2 Chocolate 10

Input: Nothing

Purchase
Input: Nothing
Display product menu
ShowMenu
Ask what is the
Display 0 : chicken price product to purchase

Display 1 : milk price Ask the quantity of that product.

Display 2 : chocolate price Calculate and display


price = unit-price * quantity

Output: Nothing Output: The price of the purchase 67


The showMenu() function
Product ID Product Unit price
Remember, we have divided our complex 0 Chicken 20
system into smaller sub-tasks (Easier problems), 1 Milk 6.5
and we can conquer each sub-tasks one by one.
2 Chocolate 10
Like in this showMenu() function, we only worry
about menu display inside this function.

Input: Nothing Global variables


ShowMenu chicken=20
milk=6.5
Display 0 : chicken price chocolate=10
def showMenu():
print("----------- Menu -----------")
Display 1 : milk price
print("0: Chicken. $" , chicken )
print("1: Milk. $" , milk)
Display 2 : chocolate price print("2: Chocolate. $" , chocolate )
print("----------------------------" )

The showMenu() function


Output: Nothing
68
Input: Nothing

The purchase() function Purchase

Display product menu


def purchase():
showMenu() Ask what is the
product to purchase
product_code = int(input("Please enter the code of product: "))
quantity = int(input("Please enter the quantity: "))
Function with no input arguments Ask the quantity of that product.
if (product_code == 0):
The purchase() function has no input arguments,
price = chicken * quantity Calculate and display
elif (product_code == 1):
it will ask user for product code and quantity and price = unit-price * quantity
price = milk * quantity
calculate the value of purchasing one type of
elif (product_code == 2):
price = chocolate *product.
quantity
Output: The price of the purchase
print("Added $",price)

return price

The purchase() function

69
Input: Nothing

The purchase() function Purchase

Display product menu


def purchase():
showMenu()
Call the showMenu() function Ask what is the
product to purchase
product_code = int(input("Please enter the code of product: "))
This is the advantage
quantity = int(input("Please enter the of divide and"))
quantity: conquer!
Ask the quantity of that product.
if (product_code == 0):
Now we only need to call the function
price = chicken * quantity Calculate and display
showMenu()
elif (product_code == 1): to display the product menu!
price = unit-price * quantity
price = milk * quantity
elif (product_code == 2):showMenu() requires no input arguments,
Since
price = chocolate * quantity
calling it just need an empty bracket() .
Output: The price of the purchase
print("Added $",price)

return price

The purchase() function

70
Input: Nothing

The purchase() function Purchase

Display product menu


def purchase():
showMenu() Ask what is the
product to purchase
product_code = int(input("Please enter the code of product: "))
quantity = int(input("Please enter the quantity: "))
Ask the quantity of that product.
if (product_code == 0):
price = chicken * quantity Calculate and display
Two local variables created
elif (product_code == 1): price = unit-price * quantity
price = milk * quantity
2):that product_code and quantity are
Note
elif (product_code ==
price = chocolate * local
two quantity
variables in purchase() function.
Output: The price of the purchase
print("Added $",price)

return price

The purchase() function

71
Input: Nothing

The purchase() function Purchase

Display product menu


def purchase():
showMenu() Ask what is the
product to purchase
product_code = int(input("Please enter the code of product: "))
quantity = int(input("Please enter the quantity: "))
Ask the quantity of that product.
if (product_code == 0):
price = chicken * quantity Calculate and display
elif (product_code == 1): price = unit-price * quantity
price = milk * quantity
elif (product_code == 2):
price = chocolate * quantity
Output: The price of the purchase
print("Added $",price)

return price Calculate price accordingly


The purchase() function
In these statements note that price is a local variable in
purchase(), while the chicken, milk and chocolate are
global variables.
Since we are not updating the value of the global variables, we do
not need to use the global keyword and we are still accessing the
global variables. 72
Input: Nothing

The purchase() function Purchase

Display product menu


def purchase():
showMenu() Ask what is the
product to purchase
product_code = int(input("Please enter the code of product: "))
quantity = int(input("Please enter the quantity: "))
Ask the quantity of that product.
if (product_code == 0):
price = chicken * quantity Calculate and display
elif (product_code == 1): price = unit-price * quantity
price = milk * quantity
elif (product_code == 2):
price = chocolate * quantity
Output: The price of the purchase
print("Added $",price)

return price Return the calculated price


The purchase() function
We would like to return the calculated price value to function
caller.
We will expect function caller to use purchase() in an expression,
which purchase() will resolve to the amount added in the purchase
of one type of item. E.g., 73
total += purchase()
The checkout() function
Displays welcome Input: total price
message
Checkout

Display total price

Yes Handle purchase


Purchase? Calculate tax = total price * 0.05
of one product
No Display the tax

Display the final amount


Handle checkout (total + tax)

Output: Nothing

74
The checkout() function
Input: total price
Checkout
def checkout(total):
print("Purchase amount $",total) Display total price
tax = total * 0.05;
print("Tax (tax rate is 5%) $",tax)
print("---------------") Calculate tax = total price * 0.05
print("Total $" ,( total + tax ))
print("Thank you!")
Display the tax

The checkout() function Display the final amount


(total + tax)

Output: Nothing

75
The checkout() function
Input: total price
Checkout
def checkout(total):
print("Purchase amount $",total) Display total price
tax = total * 0.05;
print("Tax (tax rate is 5%) $",tax)
print("---------------") Calculate tax = total price * 0.05
print("Total $" ,( total + tax ))
print("Thank you!")
Display the tax

The checkout() function Display the final amount


(total + tax)

Output: Nothing

76
The checkout() function
Input: total price
Checkout
def checkout(total):
print("Purchase amount $",total) Display total price
tax = total * 0.05;
print("Tax (tax rate is 5%) $",tax)
print("---------------") Calculate tax = total price * 0.05
print("Total $" ,( total + tax ))
print("Thank you!")
Display the tax

The checkout() function Display the final amount


(total + tax)

Output: Nothing

77
The checkout() function
Input: total price
Checkout
def checkout(total):
print("Purchase amount $",total) Display total price
tax = total * 0.05;
print("Tax (tax rate is 5%) $",tax)
print("---------------") Calculate tax = total price * 0.05
print("Total $" ,( total + tax ))
print("Thank you!")
Display the tax

The checkout() function Display the final amount


(total + tax)

Output: Nothing

78
The main() function
Displays
welcome def main():
message print("***********************************")
print("* Welcome to Kit's supermarket! *")
print("***********************************")

Yes Handle choice = 0


Purchase? purchase of total = 0
one product while( choice != 2 ):
No print("------------------------")
print("\t 1: Purchase. ")
print("\t 2: Checkout. ")
Handle
checkout
print("------------------------")

choice=int(input("Please select (1 or 2): "))

if ( choice == 1 ):
total = total + purchase()
print("Current amount $",total)
elif( choice == 2 ):
checkout(total)
The main() function
79
The main() function
Displays
welcome def main():
message print("***********************************")
print("* Welcome to Kit's supermarket! *")
print("***********************************")

Yes Handle choice = 0


Purchase? purchase of total = 0
one product while( choice != 2 ):
No print("------------------------")
print("\t 1: Purchase. ")
print("\t 2: Checkout. ")
Handle
checkout
print("------------------------")

choice=int(input("Please select (1 or 2): "))

if ( choice == 1 ):
total = total + purchase()
print("Current amount $",total)
elif( choice == 2 ):
checkout(total)
The main() function
80
The main() function
Displays
welcome def main():
message print("***********************************")
print("* Welcome to Kit's supermarket! *")
print("***********************************")

Yes Handle choice = 0


Purchase? purchase of total = 0
one product while( choice != 2 ):
No print("------------------------")
print("\t 1: Purchase. ")
print("\t 2: Checkout. ")
Handle
checkout
print("------------------------")

choice=int(input("Please select (1 or 2): "))


We use the local variable total to keep the
current sub-total. if ( choice == 1 ):
total = total + purchase()
Since purchase() will return the price of a print("Current amount $",total)
purchase, we add it to the total variable. elif( choice == 2 ):
checkout(total)
The main() function
81
The main() function
Displays
welcome def main():
message print("***********************************")
print("* Welcome to Kit's supermarket! *")
print("***********************************")

Yes Handle choice = 0


Purchase? purchase of total = 0
one product while( choice != 2 ):
No print("------------------------")
print("\t 1: Purchase. ")
print("\t 2: Checkout. ")
Handle
checkout
print("------------------------")

choice=int(input("Please select (1 or 2): "))

if ( choice == 1 ):
total = total + purchase()
print("Current amount $",total)
elif( choice == 2 ):
checkout(total)
The main() function
82
ENGG1330 Supermarket
Product ID Product Unit price ***********************************
* Welcome to Kit's supermarket! *
0 Chicken 20 ***********************************
------------------------
1 Milk 6.5 1: Purchase.
2: Checkout.
2 Chocolate 10 ------------------------
Please select (1 or 2): 1
Products in supermarket ----------- Menu -----------
0: Chicken. $ 20
1: Milk. $ 6.5
2: Chocolate. $ 10
----------------------------
Please enter the code of product: 0
Please enter the quantity: 10
Added $ 200
Current amount $ 200
------------------------
1: Purchase.
2: Checkout.
------------------------
Please select (1 or 2): 2
Purchase amount $ 200
Tax (tax rate is 5%) $ 10.0
---------------
Total $ 210.0
Thank you!

83
ENGG1330 Supermarket
*********************************** Please enter the code of product: 1
* Welcome to Kit's supermarket! * Please enter the quantity: 10
*********************************** Added $ 65.0
------------------------ Current amount $ 125.0
1: Purchase. ------------------------
2: Checkout. 1: Purchase.
------------------------ 2: Checkout.
Please select (1 or 2): 1 ------------------------
----------- Menu ----------- Please select (1 or 2): 2
0: Chicken. $ 20 Purchase amount $ 125.0
1: Milk. $ 6.5 Tax (tax rate is 5%) $ 6.25
2: Chocolate. $ 10 ---------------
---------------------------- Total $ 131.25
Please enter the code of product: 0 Thank you!
Please enter the quantity: 3
Added $ 60
Current amount $ 60 Sample output (continue)
------------------------
1: Purchase.
2: Checkout.
------------------------ X3 X 10
Please select (1 or 2): 1
----------- Menu -----------
0: Chicken. $ 20
1: Milk. $ 6.5
2: Chocolate. $ 10
----------------------------
= $131.25 (with tax)
84
ENGG1330 Supermarket
Well…Can we try to make the supermarket.py
more realistic? Like, how about if I have 10,000
products to sell in the supermarket?
0 1 2 3 4 5 6 7 8 9 …
price 20 6.5 10 18.5 6.5 5.5 12 5.4 4.8 4.6 …
name Chicken Milk Chocolate Pasta Sugar Salt Eclipse Coca cola Pepsi Fanta …

Idea: Let’s try not use global variables


and define two local lists (name and
price) in main() function.
85
Chapter 7A.

End
ENGG 1330 Computer Programming I
Dr. Chui Chun Kit and Dr. Dirk Schnieders

Department of Computer Science, The University of Hong Kong

Slides prepared by - Dr. Chui Chun Kit (http://www.cs.hku.hk/~ckchui/) and Dr. Dirk Schnieders for students in ENGG1330. For other uses, please email : ckchui@cs.hku.hk

You might also like