Chapter 5 PythonFunctions
Chapter 5 PythonFunctions
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.
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.
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
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).
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
12
Define our own functions
Syntax:
def function_name(arg1, arg2, …, argN):
statement_body
13
Executing a function
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.
16
A function can call other functions
17
Function with arguments
18
Function with arguments
x=a
y=b
19
Another way to exit a function call: return
with a value
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.
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.
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.
25
A more complicated example
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
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
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
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
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.
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