0% found this document useful (0 votes)
5 views44 pages

8 - Function 2

This document covers the concept of functions in Python, including how to define, call, and utilize functions with various parameters and return values. It explains the scope of variables, the use of recursive and nested functions, and the difference between local and global variables. Additionally, it provides examples of function usage and outlines the importance of functions in creating modular and reusable code.

Uploaded by

8xk5mzmjmm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views44 pages

8 - Function 2

This document covers the concept of functions in Python, including how to define, call, and utilize functions with various parameters and return values. It explains the scope of variables, the use of recursive and nested functions, and the difference between local and global variables. Additionally, it provides examples of function usage and outlines the importance of functions in creating modular and reusable code.

Uploaded by

8xk5mzmjmm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Function

FBT0015
STRUCTURED ALGORITHM
& PROGRAMMING
Learning Outcomes

 Upon completion of this lecture, students will be able to:


✓ grasp the basic concept of function
✓ define and call functions in Python
✓ apply functions with multiple arguments including list
and return multiples values from function, in Python
✓ describe scope of variables ,recursive and nested
functions concepts
Introduction
In finding the sum
of integers from
1 to 10,
20 to 37, and
35 to 49,
your code could be
written as -----------→
Introduction
(cont..)
 The same code
could be re-write
with function and
becomes ---------→
 The code to
calculate each
summation is similar.
However, the value
to be processed and
its result will be
different.
 You could write the
commonly used
code once, reuse it
by defining a
function and then,
call it.
Defining a Function

 A function definition consists of the function’s name, parameters


and body.

function formal
name parameters
 The syntax for defining a function is:
function
header

function
body
(need to be indented)
return value
Defining a Function (cont..)

 A function contains :
 header
begins with the def keyword, followed by the function’s
name and parameters, and ends with a colon.
the variables in the function header are known as formal
parameters or simply parameters. A parameter is like a
placeholder. When a function is invoked, the caller will pass
a value to the parameter. This value is referred to as an
actual parameter or argument. Parameters are optional.
 body includes a collection of statements that define what the
function does.
 Functions may or may not return a value. If a function returns a
value, it is called a value-returning function.
#define function without parameter Function
def Welcome(): definition
print('Welcome to LalaLand')

#define function with parameters


def WriteName(fname, mname, lname):
print(fname+'',mname+'',lname+'')

#define function with parameter of different data types


def WriteAge(age,gender):
print('Age:',age,'\nGender:',gender)

#define function with default parameter


def WriteNationality(location,nationality="Malaysian"):
print('Although you live in', location,’ we know you are ',nationality,'.')

Welcome()#call function without argument


WriteName('Kim','Nam','Joon') #call function with arguments
firstname='Kim’; middlename='Tae’; lastname='Hyung’
WriteName(firstname,middlename,lastname) #call function-variable arguments
WriteAge(23,'male') #call function with arguments of different datatype
country='Korea'
WriteNationality(country) #call function
THE
OUTPUT
Calling a function

 To use a defined function, you must call or invoke it.


functionname arguments(if any ,as per declared in function definition)

largerint(3,4)#call function
 How to call a function?
If the function returns a value, a call to that function is usually
treated as a value. It could be assigned to a variable.
For Example:
larger = largerint(3,4)
or display on screen as
print(largerint(3,4))
Calling a function (cont..)

 How to call a function?


If a function does not return a value, the call must be a function
call statement.
For example:
largerVal(3,4)
or the use of built in ‘print’ function does not return a value.
The following call function print the statement
“programming is fun”
Calling a function (cont..)

When a program calls a function, program control is transferred to the called


function. A called function return control to the caller when its return
statement is executed, or the function execution is complete.

def largerint(num1,num2):
if num1>num2: result=num1
else: result=num2
return result

def main():
i=5; j=2
k= largerint(i,j)
print('The larger number of ', i ,' and', j , ' is ', k)

main()
Output:
..Thinking Time..

Write a program that will offer 4 options to user.


User may opt to calculate perimeter of rectangle, calculate
area of triangle, convert Celsius to Fahrenheit or convert
Fahrenheit to Celsius.
You may use the formula below:
❑ calculate perimeter of rectangle,
perimeter=(2*base) + (2*height)
❑ calculate area of triangle, area=(base*height)/2
❑ convert Celsius to Fahrenheit , T(°F) = T(°C) × 1.8 + 32
❑ convert Fahrenheit to Celsius, T(°C) = (T(°F) - 32) / 1.8

Each option should be executed by a specific function.


Functions with or without Return Values

Programs below defines a function named printGrade and


invokes it to print the grade for a given score.
Without Return Values

With Return Values


Functions with or without Return Values
(cont..)

 A function does not have to return a value.


 Function that does not return a value is commonly known as a
void function.
 Technically, if a function does not return a value, by default, it
returns a special value None.
 The None value can be assigned to a variable to indicate that
the variable does not refer to any object.
 For example, the output of the following program is None,
because there is no return statement in function sum. By default,
it returns None.
Functions with or without Return Values
(cont..)

 If the function is to return a value, the return value of a Python


function can be any Python object. A function can return
numeric values (int, float, and complex values), collections and
sequences of objects (list, tuple, dictionary, or set objects), user-
defined objects, classes, functions, and even modules or
packages.
 You may add the keyword return before the value that is to be
returned to the caller.
Functions with or without Return Values
(cont..)
#a function with return value
def largerint(num1,num2):
if num1>num2:
return num1
else:
What will be the output of the return num2
#a function without return value
program??
def largervalue(num1,num2):
if num1>num2:
print('Largest value is', num1)
else:
print('Largest value is', num2)

#call functions
print (largerint(18,9))
largerint(18,9)
largeAns=largerint(18,9)
print ('inside largeAns is ', largeAns)

print (largervalue(10,5))
largervalue(10,5)
largeVal=largervalue(10,5)
print ('inside largeVal is ', largeVal)
Functions with or without Return Values
(cont..)

 A return statement is not


needed for a None function, but
it can be used for terminating
the function and returning
control to the function’s caller.
 The syntax is simply return or
return None
 This is rarely used, but it is
sometimes useful for
circumventing the normal flow
of control in a function that
does not return any value.
 For example, printGrade has a
return statement to terminate
the function when the score is
invalid. Output:
Function Returns Multiple Values

 Python return statement can return multiple values.


 When a function is invoked, the function can pass back the
returned values by using a simultaneous assignment during the
invocation.

Output:
..Thinking Time..

Write a program that will offer 4 options to user.


User may opt to calculate perimeter of rectangle, calculate area
of triangle, convert Celsius to Fahrenheit or convert Fahrenheit
to Celsius.
You may use the formula below:
❑ calculate perimeter of rectangle,
perimeter=(2*base) + (2*height)
❑ calculate area of triangle, area=(base*height)/2
❑ convert Celsius to Fahrenheit , T(°F) = T(°C) × 1.8 + 32
❑ convert Fahrenheit to Celsius, T(°C) = (T(°F) - 32) / 1.8

Each option should be executed by a specific function. Each


function will return the result of the calculation or conversion to
be display by a function called displayResult.
Function Returning a List as value

 When a function returns a list, the list’s reference value is returned.


 For example, the following function returns a list that is the reversal
of another list.

Output:
Positional & Keyword Arguments

 When calling a function, you will need to pass arguments to


parameters as per in function definition.
 There are two kinds of arguments:
 positional arguments
requires the arguments to be passed in the same order as their
respective parameters in the function definition header.
 keyword arguments
passing each argument in the form name=value and can appear
in any order.
It is possible to mix positional arguments with keyword arguments, but
the positional arguments cannot appear after any keyword arguments
Positional & Keyword Arguments
(cont..)
Output:
Positional arguments

Keyword arguments

Mix arguments
..Thinking Time..

What will happen if we run this code…??

def nPrintln(*message):
print(message[3])
nPrintln ('sayang','saya','say','saying','sayung')

when you do not know how many arguments to get from your
caller, you may use Arbitrary Arguments (*message).
Passing Arguments by Reference
Values

 When you invoke a function with arguments, the reference value of each
argument is passed to the parameter (pass-by-value).
 If the argument is a number or a string, the argument is not affected,
regardless of the changes made to the parameter inside the function.

Output:
..Thinking Time..

Trace the output of the codes


Passing Lists to Functions

When passing a list to a function, the contents of the list may


change after the function call, since a list is a mutable object.

Output:
Scope of Variables

 Local Variable
 variable created inside a function
 can only be accessed within a function where its being created.
 the scope of local variable starts from its creation and continues to the
end of the function that contains the variables.
 a local variable could be bind in the global scope or a variable in a
function can be use outside the function by using a global statement
(refer scope of variable-Example 3)

 Global variables
 variable created outside all functions
 accessible by all functions in their scope.
Scope of Variables (cont..)

Global variable is created before function definition and accessible


within and outside any functions. Eg: globalVar
Local variable is created in the function and accessible within the
function of where its being created. Eg.localVar
Attempt to access the local variable from outside of the function
causes an error.
Scope of Variables (cont..)

Global variable x is created before the function and a local


variable with the same name, x is created in function,f1.
Global variable, x is not accessible by f1.f1 process its local
variable x. Outside the function, the global variable x is being
accessible.
Scope of Variables (cont..)

Global variable x is created before the function and x is bound


in the function by using global statement. x in the function is the
same as x outside of the function. Thus, when x changed in
function increase, it changed x that was declared outside the
function. The program prints 2 in the function and outside of the
function.
..Thinking Time..
..Thinking Time..
..Thinking Time..

Write a function that will find the smallest element from a list of integers
and returns the index of the smallest element found. Use the following
function header:

Write a test program that prompts the user to enter a list of number of
data type integer, invokes the function to return the index of the
smallest element, and displays the index.
Recursive function

Recursive module: A module that calls itself


Example 1: Calculate Factorial Without Recursive
n i product Display on
def factorial(n): screen

product=1 5 - 1 -

for i in range (1,n+1): 1 1 1

product*=i 2 2 2

print (product) 3 6 6

4 24 24

factorial(5) 5 120 120

Output:
Recursive function (cont..)

Example 1: Calculate Factorial With Recursive

 Example 1: Factorial With Recursive Output:


Recursive function (cont..)
n=5
factorial(5) 120 Output:

5 * factorial(4) 24 print(result) 120

4 * factorial(3) 6 print(result) 24

3 * factorial(2) 2 print(result) 6

2 * factorial(1) 1 print(result) 2

factorial=1 print(result) 1
Recursive function (cont..)

Example 2: Calculation Without Recursive


Output:
def tri_recursion(k):
result=0
for i in range (1,k+1):
result+=i
print (result)
tri_recursion(6)
Recursive function (cont..)

Example 2: Calculation With Recursive


Output:
..Thinking Time..

Write a recursive function that, given an input value


of N, computes N+N-1…..+2+1
Eg: N=5, 5+ 4+3+2+1
Output:
..Thinking Time..

Write a function C(N, R) that returns the numbers of


different ways R item can be selected from a group
of N items. Formula for C(N,R) is as follow:
C(N,R)= N!
---------------
R!(N-R)!
Eg: C(5,3)= 5!
-----------------
3!(2)!
HINT: reuse the function factorial in our class example.
Possible Solutions

Output:
Nested Function
 Occur when another function declared in a function. Variable for inner function
can be used by itself only. Any variables from main program declaration and
outer functions can be used by inner functions.

Def functionOuter:
Def functionInner:
…..functionInnerBody……..

…..functionOuterBody……..

main
Nested Function (cont..)

Output:

 Example:
Summary
A function header begins
Functions help in making
with the def keyword
program modular and A function is called a void or
followed by function’s
reusable, as that is one of None function if it does not
name and parameters, then
the central goals in software return a value.
ends with a colon.
engineering
Parameters are optional.

A return statement can be A function’s arguments can


A variable created in a
used in a void function for be passed as positional
function is called local
terminating the function arguments or keyword
variable. Global variables is
and returning to the arguments. When you
created outside all functions
function’s caller. Python invoke a function with a
and are accessible to all
return statement can return parameter, the argument is
functions in their scope.
multiple values. pass-by-value.

Python accepts recursive Nested functions occur


function where a defined when another function is
function can call itself. declared in a function.

You might also like