Python Functions
COMP1117B Computer Programming
1
Divide and conquer
Recall the program for calculating the BMI.
Read in height and
weight of user.
We can tackle the problem by dividing
our program into 3 sub-tasks.
Calculate the BMI
We will treat each part as a smaller
problem and tackle (conquer) the smaller
problems one by one.
Output the category
based on the BMI
Flowchart
Divide and conquer
Read in height and Input: nothing
weight of user.
Obtain user input
height (in m) and
Calculate the BMI 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
>22.9 Overweight
Input: BMI
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)
2. The objective of the sub-task (But not the process of how the task is done).
3. Output(s)
Input: height and weight Calculate the BMI Output: BMI
Problem Solving Technique:
At the time you define 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
Built-in functions:
• type(), int(), float(), str(), bool(), list(), tuple(), set(), dict(), range(), input()
Some mathematical functions from the module math:
• sin(), cos(), sqrt(), log(), exp(), pow()
7
What do you need to use these functions?
You need a definition for the function
What this function is for?
What is the syntax of this function?
What inputs (i.e., function parameters) should be
provided to this function?
Types of the inputs are important.
What outputs (i.e., return values) will the function
produce?
8
[[Link] Types of the return values are important.
What do you need to use these functions?
Try inputting -1 to this program.
What do you get?
9
[[Link]
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.
• input(str) : one optional string argument (i.e., it can go without any argument)
• sqrt(m) : one float argument.
• range(start, stop, step) : three int arguments, start & step are optional.
10
Composition of functions
The return value of a function can be used directly as an argument
of another function.
11
Useful functions from the module random
random():
• return a random float number R such that 0.0 ≤ R < 1.0
randint(a, b):
• return a random (arbitrary) integer N such that a ≤ N ≤ b.
choice(mylist):
• return a random item in the list mylist.
12
Useful functions from the module random
13
Define our own functions
Syntax
def function_name (arg1, arg2, … , argN):
statement_1
statement_2 Note the indentation for the
… function body
return statement
When defining a function, we need:
• 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 (separated by
commas)
• Return statement (optional) for returning value(s) back to function caller.
Usually returning the calculated / processed data back to the function caller.
14
Define our own functions
Example:
This is a complete Python program
Defining a function
named print_row
Body of the
main program
Note: A function must be defined before it is called.
15
Executing a function
Execution of the main
program starts here.
The first statement is
a function call and
hence execution of
the main program is
suspended.
16
Executing a function
Execution jumps to the
beginning of the called
function,
and its statements are
executed one by one.
17
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.
18
A function can call other functions
19
Function with arguments
When the function is called, it executes the two assignments implicitly before
executing the body:
x=a
y=b
i.e., the actual arguments (a, b) are copied to the function parameters (x, y) 20
Function with arguments
x=a
y=b
21
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.
22
Another way to exit a function call:
return with a value
Suppose m = 4
1
2
x = m (== 4)
True
23
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.
24
Example: To check if a number is prime
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
25
Example: To check if a number is prime
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
26
Example: To check if a number is prime
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 is this statement redundant?
27
Example: To check if a number is prime
The program starts running
from here;
these five lines of statements
form the main part of the
program.
28
The main program body
Many programmers prefer
defining a function call “main()”,
which contains the main part of
the programs.
29
The main program body
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.
30
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 called.
return False
else: i 15 % i return?
return True 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!!!
31
Correct version
Let’s dry-run it with 15…
def is_prime(a):
for i in range(2,a): Suppose is_prime(15) is called.
if a % i == 0:
return False i 15 % i return?
return True 2 1 -
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 numbers are tried.
32
Correct version
Let’s dry-run it with 5…
def is_prime(a):
for i in range(2,a): Suppose is_prime(5) is called.
if a % i == 0:
return False i 15 % i return?
return True 2 1 -
3 2 -
4 1 -
Finished for loop but still cannot
“return False”. So go to the statement
outside for loop and “return True”.
33
Local vs. Global 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.
The variable "combine" is initialized inside the function
print_twice() and therefore its scope is within the function only. An
error is raised when the variable is used in the main program body.
34
Local vs. 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
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!
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!
A global variable with name avar
A different variable, which is a
local variable of func(), and its name
is also avar.
37
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 want to change the
value of the global variable avar to 70
here inside func()?
38
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!
But, what if we indeed want to change the
value of the global variable avar to 70
here inside func()?
39
map: applies a function to all items in an input list
Syntax:
map(function_to_apply, list_of_inputs)
40
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)
b = [4,5,6] 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: [4, 10, 18] [4, 10] Output:
[4, 10, 18] TypeError: multiply()
missing 1 required
positional argument:
'y' 41
filter: creates a list for which a function returns true
Syntax:
filter(function_to_apply, list_of_inputs)
42
filter: creates a list for which a function returns true
We can only filter 1 list / tuple with a function that takes 1 input
argument.
def smaller(x,y):
if x < y:
return True
return False
a = [1,2,3]
b = [4,5,6]
c = filter(smaller,a,b) This is wrong!
print(list(c))
Output:
TypeError: filter expected 2 arguments, got 3
43
Define one line function using lambda
Syntax:
function_name = lambda argument: expression on the argument
44
Use lambda with map, filter
45
Checking within a one-line function
46
Checking within a one-line function
47
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.
Ans: sum(list(map(int, str(int(input())*2))))
48
Challenge: A question in a past midterm
Ans: sum(list(map(int, str(int(input())*2))))
Output:
Try this:
y = input() 123
print(int(y)) 123
print(int(y)*2) 246
print(str(int(y)*2)) 246
print(map(str(int(y)*2))) <map object at 0x0000012BC8D25FF0>
print(list(map(str(int(y)*2)))) [2, 4, 6]
print(sum(list(map(str(int(y)*2))))) 12
49
One more challenge
Given two lists of integers, print the integers that are in both lists.
50
Reading Assignment
Think Python, Chapter 3
51