Professional Documents
Culture Documents
Chapter 7A - Functions
Chapter 7A - Functions
Functions
ENGG 1330 Computer Programming I
Dr. Chui Chun Kit and Dr. Dirk Schnieders
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.
2
Section 7A.1
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.
4
Divide and conquer
BMI Category
<18.5 Underweight
Within 18.5 and 22.9 Normal
>22.9 Overweight
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.
2. The objective of the sub-task (But not the process of how the task is done).
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
Output: BMI
13
The calculate_bmi() function
Input: height (in m) and weight (in kg) Input: height (in m) and weight (in kg)
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)
16
Calling the calculate_bmi() function
def calculate_bmi (height, weight):
bmi = weight / (height * height)
return bmi
17
Calling the calculate_bmi() function
def calculate_bmi (height, weight):
bmi = weight / (height * height)
return bmi
18
Calling the calculate_bmi() function
def calculate_bmi (height, weight):
bmi = weight / (height * height)
return 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
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
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
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()
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
28
Example 2
def calculate_bmi (h, w):
bmi_val = w / (h * h) Local variables in the main() function
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")
main()
print("End of program")
main()
print("End of program")
main()
print("End of program")
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()
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()
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.
main()
Output: Nothing 54
Section 7A.5
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.
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()
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 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(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
Input: Nothing
Purchase
Input: Nothing
Display product menu
ShowMenu
Ask what is the
Display 0 : chicken price product to purchase
return price
69
Input: Nothing
return price
70
Input: Nothing
return price
71
Input: Nothing
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
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
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
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
Output: Nothing
78
The main() function
Displays
welcome def main():
message print("***********************************")
print("* Welcome to Kit's supermarket! *")
print("***********************************")
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("***********************************")
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("***********************************")
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 …
End
ENGG 1330 Computer Programming I
Dr. Chui Chun Kit and Dr. Dirk Schnieders
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