Chapter 5.
Python
Functions
2023-2024
COMP1117A Computer Programming
Dr. T.W. Chim (twchim@cs.hku.hk) & Dr. H.F. Ting (hfting@cs.hku.hk)
Department of Computer Science, The University of Hong Kong
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
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
3
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
4
Divide and conquer BMI
<18.5
Category
Underweight
Within 18.5 and 22.9 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
Output: Nothing
5
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. 6
Some functions we’ve learned
Build-in functions:
type(), int(), float(), str(), bool(), list(), tuple(), set(), dict(),
range()
Some mathematical functions from the module math:
sin(), cos(), sqrt(), log(), exp(), pow()
7
Some useful functions from the module
random
randint(a, b): “return” a random (arbitrary) integer N such that
a ≤ N ≤ b.
random(): return a random float number R such that
0.0 ≤ R < 1.0
choice(mylist): return a random item in the list mylist.
8
Some useful functions from the module
random
9
More about functions
A function must have a unique name. We call a function by its
name.
A function may or may not “return” a value.
sqrt(m): returns the square root of m
print(“Hello”): does not return any value (but print the string “Hello” on
screen).
A function may need some arguments, and the value it returns
depends on these arguments.
random(): no argument
sqrt(m) has one float argument.
randint(a, b): has two int arguments.
10
Composition of functions
The return value of a function can be used directly as an
argument of another function.
11
Define our own functions
Keyword to
define a def function_name (arg1, arg2, … , argN):
function statement_1
statement_2 must be indented.
…
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
Define our own functions
Syntax:
def function_name(arg1, arg2, …, argN):
statement_body
13
Executing a function
Execution of the main
program is suspended
here.
14
Executing a function
Execution jumps
to the beginning
of the called
function,
and its statements
are executed one
by one.
15
Executing a function
When all the statements
of the function are
executed, control returns
back to the suspended
point in main, and the
following statement is
executed.
Note: A function must be defined before it is called.
16
A function can call other functions
17
Function with arguments
When the function is called, it will
execute the two assignments
implicitly before executing the body:
x=a
y=b
18
Function with arguments
x=a
y=b
19
Another way to exit a function call: return
with a value
When a return statement is
executed, the function call
will be terminated
immediately, and the control
will be returned to the calling
statement. The value (of the
expression) associated with
the return statement is the
value returned by the
function call.
20
Another way to exit a function call: return
with a value
x = m (== 4)
Suppose m = 4
True
21
Returning multiple values
To return multiple values from a function, just specify each
value separated by comma (,) after the return keyword.
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.
22
A more complicated example
Given an integer m > 1 as the argument, is_prime(m)
returns True if m is a prime number, and returns False otherwise.
Recall that an integer m > 1 is a prime if it is divisible only by
1 and itself.
E.g., is_prime(12) ➔ False
is_prime(23) ➔ True
23
A more complicated example
Given an integer m > 1 as the argument, is_prime(m)
returns True if m is a prime number, and returns False otherwise.
In-class exercise: Implement is_prime(m) as follows:
for i = 2, 3, 4, ..., m – 1:
if i divides m:
return False
if still alive when i == m:
return True
24
A more complicated example
Given an integer m > 1 as the argument, is_prime(m)
returns True if m is a prime number, and returns False otherwise.
In-class exercise: Implement is_prime(m) as follows:
for i = 2, 3, 4, ..., m – 1:
if i divides m:
return False
if still alive when i == m:
return True Why we can do
that?
25
A more complicated example
The program starts
running from here;
these five lines of
statements form the
main part of the
program.
26
A more complicated example
Many programmers
prefer defining a
function call “main()”,
which contains the
main part of the programs.
27
A more complicated example
In some Python programs,
you may see this line.
This is for programs that
can be included in modules,
and that is out of our scope.
28
Why is the following incorrect???
def is_prime(a): Let’s dry-run it with 15…
for i in range(2,a):
if a % i == 0: Suppose is_prime(15) is
return False
else: called.
return True i 15 % i return?
2 1 True
This is obviously wrong!
This implementation is equivalent to the following description:
Go through all numbers from 2 to a – 1, if a is divisible by that number, conclude that it is not
prime. Otherwise, conclude that it is prime.
➔ The conclusion is made too soon!!!
29
Correct version
def is_prime(a): Let’s dry-run it with 15…
for i in range(2,a):
if a % i == 0: Suppose is_prime(15) is
return False
return True called.
i 15 % i return?
2 1 Nil
3 0 False
This implementation is equivalent to the following description:
Go through all numbers from 2 to a – 1, if a is divisible by that number, conclude that it is not
prime. Otherwise, continue to try the next number. Conclude that it is prime only if all number
are tried.
30
Correct version
def is_prime(a): Let’s dry-run it with 5…
for i in range(2,a):
if a % i == 0: Suppose is_prime(5) is
return False called.
return True
i 15 % i return?
2 1 Nil
3 2 Nil
4 1 Nil
Finished for loop but still cannot “return
False”. So go to the statement outside for
loop and “return True”.
31
Local vs. Global variables
Local variables: Local variables are those which are initialized inside a
function and belongs only to that particular function. It cannot be accessed
anywhere outside the function.
32
Local vs. Global variables
Global variables: Global variables are those which are defined outside
any function, and which are accessible throughout the program i.e., inside
and outside of every function
33
Local vs. Global variables
We used to say that every variable in a Python program must
have a unique name. But it is not 100% true!
34
Local vs. Global variables
We used to say that every variable in a Python program must
have a unique name. But it is not 100% true!
A global variable with name avar
A different variable, which is a
local variable of func, and its name
is also avar.
35
Local vs. Global variables
We used to say that every variable in a Python program must
have a unique name. But it is not 100% true!
A global variable with name avar
A different variable, which is a
local variable of func, and its name
is also avar.
But, what if we indeed what to change to value of
the global variable avar to 70 here?
36
Local vs Global variables
We used to say that every variable in a Python program must
have a unique name. But it is not 100% true!
37
map: applies a function to all items in an input list
Syntax:
map(function_to_apply, list_of_inputs)
38
map: applies a function to all items in an input list
In general, we can map a function with n input arguments to n lists /
tuples.
Size of the n lists / tuples can be different.
Size of output of map function = smallest size of the n lists / tuples
The function is mapped to the values in the lists / tuples in order.
def multiply(x,y): def multiply(x,y): def multiply(x,y): def multiply(x,y):
return x * y return x * y return x * y return x * y
a = [1,2,3] a = (1,2,3) a = (1,2,3) a = (1,2,3)
b = [4,5,6] b = (4,5,6) b = (4,5) b = (4,5,6)
c = map(multiply,a,b) c = map(multiply,a,b) c = map(multiply,a,b) c = map(multiply,a)
print(list(c)) print(list(c)) print(list(c)) print(list(c))
Output: Output: Output: Output:
[4, 10, 18] [4, 10, 18] [4, 10] TypeError:
multiply() missing
1 required
positional
argument: 'y'
39
filter: creates a list for which a function returns true
Syntax:
filter(function_to_apply, list_of_inputs)
40
filter: creates a list for which a function returns true
We can only filter a function with 1 input argument by
mapping 1 list / tuple.
The following is wrong!
def smaller(x,y):
if x < y:
return true
return false
a = [1,2,3]
b = [4,5,6]
c = filter(smaller,a,b)
print(list(c))
Output:
TypeError: filter expected 2 arguments, got 3
41
Define one line function using lambda
Syntax:
function_name = lambda argument: expression on the argument
Example:
42
Use lambda with map, filter
43
Checking within a one-line function
44
Checking within a one-line function
45
Challenge:
A question in a past midterm
Write a complete Python program that reads an integer, then
multiply it by 2, and print the sum of the digits in the result. For
example, if the input is 123, then your program should output
12 because 123 x 2 = 246 and 2 + 4 + 6 = 12.
46
Challenge:
A question in a past midterm
47
One more challenge
Given two lists of integers, print the integers that are in both
lists.
48
Chapter 5.
END
2023-2024
COMP1117A Computer Programming
Dr. T.W. Chim (twchim@cs.hku.hk) & Dr. H.F. Ting (hfting@cs.hku.hk)
Department of Computer Science, The University of Hong Kong