ISOM Python

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 59

ISOM2007 – All Sections

Programming for Business


Analytics
Python Functions & User-Defined
Functions
Hongchuan Shen
Faculty of Business Administration
University of Macau

1
Learning Outcome
• What is a function
• Built-in Functions in Python
• User-Defined Functions
• Scope of Variable
• User-Defined Functions having
One Parameter
• Passing Values to a Function
• Functions having Several Para
meters
• Default Values in Parameters
• Boolean- and List-Valued Functi
ons
• Functions with Flexible Numbe
r of Parameters
• Functions Calling Other Functio
ns 2
• Functions that Calling Itself
Functions as Black Boxes
• A function is a sequence of instructions
with a name
• For example, the round function, contains
instructions to round a floating-point
value to a specified number of decimal
places

3
Calling Functions
• You call a function in order to execute its
instructions
price = round(6.8275, 2) # Sets result to 6.83

• By using the expression round(6.8275, 2),


your program calls the round function,
asking it to round 6.8275 to two decimal
digits

4
Calling Functions (2)
• The round function returns its result back
to where the function was called and
your program resumes execution

5
Function Arguments
• When another function calls the round
function, it provides “inputs”, such as the
values 6.8275 and 2 in the call round(6.8275, 2)
• These values are called the arguments of
the function call
• Note that they are not necessarily inputs provided by
a human user
• They are the values for which we want the function to
compute a result

6
Function Return Values
• The “result” that the round function
computes is called the return value(s)
• The return value(s) of a function is
returned to the point in your program
where the function was called
price = round(6.8275, 2)
• When the round function returns its
result, the return value is stored in the
variable ‘price’ statement)

7
The round Function as a Black
Box
• You pass the round function its necessary
arguments (6.8275 & 2) and it produces
its result (6.83)

8
The round Function as a Black
Box
• You may wonder how the round function
performs its job
• As a user of the function, you don’t need
to know how the function is implemented
• You just need to know the specification of
the function:
• If you provide arguments x and n, the function returns
x rounded to n decimal digits

9
Built-in Functions in Python
• Python has many built-in functions that are like miniature
programs.
• They receive input, process the input, and produce output
• Some built-in functions that commonly be used:
Function Example Input Output
int int(2.6) yield 2 number number
chr chr(65) yield “A” number string
ord ord(“A”) yield 65 string number
round(3.1417, 1) yield number,
round number
3.1 number

• Re-call: You can be able to learn more about built-in functions by


visit the web sites below:
• https://docs.python.org/3.8/library/index.html
• https://www.w3schools.com/python/
10
Built-in Functions in Python
• Many more of built-in functions that available all the time via
the Python interpreter.
Built-in Functions
abs() complex() getattr() len() pow() str()
all() delattr() globals() list() print() sum()
any() dict() hasattr() locals() property() super()
ascii() dir() hash() map() range() tuple()
bin() divmod() help() max() repr() type()
bool() enumerate hex() memoryvie reversed() vars()
() w()
bytearray() eval() id() min() round() zip()
bytes() exec() input() next() set() __import__(
)
callable() filter() int() object() setattr()
chr() float() isinstance() oct() slice()
classmetho format() issubclass() open() sorted()
d()
compile() frozenset() iter() ord() staticmeth
od()

• Referred to the following for the details on their usage:


11
• https://docs.python.org/3.8/library/functions.html
User-Defined Functions
• In addition to use built-in functions, we can define functions
of our own (named as user-defined functions) that return
values.

12
Syntax: Function Definition

13
Programming Tip: Function
Comments
• Whenever you write a function, you
should comment its behavior
## Computes the volume of a cube.
# @param sideLength the length of a side of the
cube
# @return the volume of the cube
#
def cubeVolume(sideLength) :
volume = sideLength ** 3
return volume
Function comments explain the purpose of the function, the
meaning of the parameter variables and the return value, as
well as any special requirements

14
The main Function
• When defining and using functions in
Python, it is good programming practice
to place all statements into functions,
and to specify one function as the
starting point
• Any legal name can be used for the
starting point, but we chose ‘main’ since
it is the required function name used by
other common languages
• Of course, we must have one statement
in the program that calls the main
function 15
Syntax: The main Function

16
Using Functions: Order (1)
• It is important that you define any function
before you call it
• For example, the following will produce a
compile-time error:
print(cubeVolume(10))
def cubeVolume(sideLength) :
volume = sideLength ** 3
return volume
• The compiler does not know that the
cubeVolume function will be defined later in
the program
17
Using Functions: Order (2)
• However, a function can be called from within another
function before the former has been defined
• The following is perfectly legal:
def main() :
result = cubeVolume(2)
print("A cube with side length 2 has
volume",
result)

def cubeVolume(sideLength) :
volume = sideLength ** 3
return volume

main()
18
Parameter Passing
• Parameter variables receive the
argument values supplied in the function
call Calling
function
• The argument value may be: o
• The contents of a variable Argument value
u
• A ‘literal’ value (2) t
• Aka, ‘actual parameter’ or argument
Parameter variable in
• The parameter variable is: Called
• Declared in the called function function
• Initialized with the value of the argument value
• Used as a variable inside the called function
• Aka, ‘formal parameter’
19
Parameter Passing Steps
result1 = cubeVolume(2)

def cubeVolume(sideLength):
volume = sideLength * 3
return volume

20
Common Error
• Trying to modify parameter variables
• A copy of the argument values is
passed (the Value is passed)
• Called function (addTax) can modify local copy
(price)
total = 10
addTax(total, 7.5);
total
cop
10.0
y

def addTax(price, rate):


tax = price * rate / 100
# No effect outside the
function
price = price + tax price
return tax; 21
10.75
Programming Tip
• Do not modify parameter variables
Many programmers find
this practice confusing

def totalCents(dollars, cents) :


cents = dollars * 100 + cents # Modifies parameter
variable.
return cents
To avoid the confusion,
simply introduce a
separate variable:
def totalCents(dollars, cents) :
result = dollars * 100 +
cents
return result

22
Test

23
Variable Scope
• Variables can be declared:
• Inside a function
• Known as ‘local variables’
• Only available inside this function
• Parameter variables are like local variables
• Outside of a function
• Sometimes called ‘global scope’
• Can be used (and changed) by code in any
function
• How
Thedo youofchoose?
scope a variable is the part of the
program in which it is visible

24
Variable Scope
• Local variables
o Created inside a function
o Exist only as long as the function is being
executed
o Recreated if the function is called again
o Parameters are all local variables
o Python checks for local variables first

25
Re-using Names for Local
Variables
• Variables declared inside one function
are not visible to other functions
• result is local to square and result is local to main
• They are two different variables and do not overlap
• This can be very confusing

def square(n):
result = n * n result
return result

def main():
result = square(3) + square(4) result
print(result)

26
Variable Scope
• Global variables
o Created outside function
o Persist between function calls
o Can be changed from inside a function
o To specify a variable as global in a function, use the
statement
global globalVariableName
o The global statement affects only the statements
following it in its function block.
o It does not allow the global variable to be altered
inside other functions.
o As a good programming practice, global variable is not
too recommended (only do it, whenever it is really be
necessary) as it will increase your burden in debugging
27
Variable Scope

These
variables
“area” not of
the same
scope

28
Variable Scope
• Example

29
Programming Tip
• There are a few cases where global variables
are required (such as pi defined in the math
module), but they are quite rare
• Programs with global variables are difficult to
maintain and extend because you can no
longer view each function as a “black box”
that simply receives arguments and returns a
result
• Instead of using global variables, use function
parameter variables and return values to
transfer information from one part of a
program to another
30
Variable Scope
Test

32
User-Defined Functions
having One Parameter
• Examples of user-defined function having one
parameter:

This issue will


be discussed in
data structure
String

33
User-Defined Functions
having One Parameter
• The call statements to invoke the two functions
from the previous slides

34
Passing Values to a Function
• If the argument in a function call is a variable, the
object pointed to by the argument variable (not the
argument variable itself) is passed to a parameter
variable.
• Therefore, if the object is immutable and the
function changes the value of the parameter
variable, no change will occur in the object pointed
to by the argument variable.
• Even if the two variables have the same name,
they are treated as entirely different variables.
Therefore, when the argument variable points to a
numeric, string, or tuple object, there is no
possibility what-so-ever that the value of the
argument variable will be changed by a function
call.
35
Passing Values to a Function
• Example (Increase a given temperature by 10)

36
Passing Values to a Function
• Example: (increase the score by 20% if score more
than 70, 10% if score more than 50 and 0% if failed,
but no score should more than 100)

37
Functions Having More than
One Parameters
• Python allows functions to receive a varying
number of arguments
• NOW, we just consider functions that must
receive a fixed number of arguments.
• When calling a function and passing
arguments by position, there must be the
same number of arguments as parameters.
• The data types of the arguments’ values must
be compatible with (and in the same order) as
the data types expected by the parameters.

38
Functions Having More than
One Parameters
• Example (Determine the payroll with 1.5 of payrate for overtime
works)

39
Functions Having More than
One Parameters
Scenario #1
 Determine the overall assessment for a number of
students until no more students
 Overall assessment make up of 3 components: exercise,
test, and exam
 Perform round-up on individual component
 If exam better than test, 20% from both exercise
and test and 60% from exam, otherwise 20% from
exercise, 40% from both test and exam.

40
Functions Having More than
One Parameters

41
Functions Having More than
One Parameters

42
Default Values in Parameters
• Some (or all) of the parameters of a function can have
default values—values that are assigned to them when no
values are passed to them.
• If the corresponding arguments are omitted when the
function is called, the default values are assigned to the
parameters.
• A typical format for a function definition using default
values is
def functionName(par1, par2, par3=value3,
par4=value4):

43
Default Values in Parameters
• Three various instance of function calls

Result Calculated
Function Call
value As
specialOperation (2, 3) 38 23 + 10 + 20
specialOperation (2, 3,
32 23 + 4 + 20
4)
specialOperation (2, 3,
17 23 + 4 + 5
4, 5)

44
Default Values in Parameters
Calculated
Function Call Result value
As
specialOperation (2, 3) 38 23 + 10 + 20
specialOperation (2, 3, 4) 32 23 + 4 + 20
specialOperation (2, 3, 4,
17 23 + 4 + 5
• Analysis
5)

• The 1st & 2nd parameters are compulsory


• The 3rd and the 4th parameters are optional
• If the 3rd parameter is not given, neither the 4th
parameter
• If the 3rd parameter not given, default to be 10
• If the 4th parameter not given, default to be 20
45
Default Values in Parameters
• Example: function specialOperation()

46
Functions with Flexible
Number of Parameters
• In addition to functions that with multi-
parameters and parameters with default
values, we may have functions with
flexible number of parameters
• For example, the built-in function max(),
can be invoked in the following ways:

47
Functions with Flexible
Number of Parameters
• User-defined functions with flexible number of
parameters can be defined by statements of
the form
def functionName ([par], *pars):
indented block of statements
Return expression
• Let’s demonstrate how can can be able to do
this with our own defined function
max_integer() that accepted a list of elements
of various data type (i.e. integer, float and
char), but with at least one input parameter.
48
Functions with Flexible
Number of Parameters
• Example: User-defined function
max_integer()
In Python 2, adding 1 to the maxint
gives the highest possible long
int and in Python 2.7, subtracting 1
from maxint gives the smallest
possible value for an integer.
Not valid in Python 3.

49
Boolean- and List-Valued
Functions
• The values returned not just only be
numbers or strings.
• It can return any type of value or even
not return anything (i.e. no return
statements).

50
Boolean- and List-Valued
Functions
• Example: function that returns a Boolean
value.

51
Boolean- and List-Valued
Functions
• Example: function that returns a List.

52
Functions Calling Other
Functions
• A function can call another function.
• When the called function terminates (that
is, after a return statement or the last
statement of the called function is
executed), the control returns to the
place in the calling function just after
where the function call occurred.

53
Function that Calling Itself
• Function that calling itself is known as
recursive function.
• It is a very powerful function to solve some
recurrence instances.
• Example: determine a factorial

54
Function that Calling Itself
• Example: Tower-of-Hanoi

55
Lambda Expression
• https://www.youtube.com/watch?
v=KR22jigJLok
Write a program
Problem Statement: Students in this course take four exams and earn
a letter grade (A+, A, A–, B+, B, B–, C+, C, C–, D+, D, D–, or F) for
each of them. The course grade is determined by dropping the lowest
grade and averaging the three remaining grades. To average grades,
first convert them to number grades, using the usual scheme A+ =
4.3, A = 4.0, A– = 3.7, B+ = 3.3, . . ., D– = 0.7, F = 0. Then compute
their average and convert it back to the closest letter grade. For
example, an average of 3.51 would be an A–.
Your task is to read four letter grades, one per line.
For example, A–
B+
C
A
For each sequence of four input lines, your output should be the letter
grade earned in the course, as just described. For example, A–.

The end of inputs will be indicated by a Grade input of Q.


59
Write a program

60
Write a program

61

You might also like