0% found this document useful (0 votes)
56 views

Chapter 6 Function - Combined

Here is a function that finds the smallest element from a list of integers and returns the index of the smallest element: ```python def find_smallest(list): smallest = list[0] smallest_index = 0 for i in range(1,len(list)): if list[i] < smallest: smallest = list[i] smallest_index = i return smallest_index ``` And here is a test program that prompts the user to enter a list and prints the index of the smallest element: ```python list = input("Enter a list of integers separated by comma: ").split(",") list = [int(x) for x in list]
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

Chapter 6 Function - Combined

Here is a function that finds the smallest element from a list of integers and returns the index of the smallest element: ```python def find_smallest(list): smallest = list[0] smallest_index = 0 for i in range(1,len(list)): if list[i] < smallest: smallest = list[i] smallest_index = i return smallest_index ``` And here is a test program that prompts the user to enter a list and prints the index of the smallest element: ```python list = input("Enter a list of integers separated by comma: ").split(",") list = [int(x) for x in list]
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

FAT0015/FBT0015

Chapter 6:Function
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 arguments including list, scope of variables, return
multiples values from function in Python
✓ describe the 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 might look like this:
Introduction (cont..)
The code to calculate each summation is similar, except that the starting
and ending are different.
You could write the commonly used code once and then reuse it by
defining a function as below:
Defining a Function
A function definition consists of the function’s name, parameters and
body.
The syntax for defining a function is:

formal
function parameters
name
function
header
function
body

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.
Defining a Function (cont..)
Example 1: Function without parameter

Function
definition

Call function Welcome


Defining a Function (cont..)
Example 2: Function with parameters
Function
definition

Call function
write3Name
Defining a Function (cont..)
Example 3: Function with parameters (different data type)

Function
definition

Call function
writeAgeGen
Calling a function
To use a defined function, you have to call or invoke it. The program that calls the function
is called a caller.
There are two ways to call a function, depending on whether or not it returns a value.
◦ If the function returns a value,
a call to that function is usually treated as a value. Ex: larger = max(3,4)
or another example of a call that is treated as a value is print(max(3,4))

◦ If a function does not return a value, the call to the function must be a function call
statement. For example, the print function does not return a value. The following call
function print

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.
Calling a function (cont..)
def max(num1,num2):
if num1>num2:
result=num1
else:
result=num2
return result

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

main()
Output:
Calling a function (cont..)
Inside the program, arguments i and j value 5 and 2.A complete program to
use function maximum. Can you spot any error?
Functions with/without Return
Values (cont..)
Programs below defines a function named printGrade and invokes it to
print the grade for a given score (one example with return value and another
one is without return value).
Without Return Values

With Return Values


Functions with/without Return
Values
A function does not have to return a value.
Function max that was discussed earlier is a function with return values.
Function that does not return a value is commonly known as a void function.
Technically, if a function does not return a value (None function) 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/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.
Functions with/without Return
Values (cont..)
The code 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:
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:
..Thinking Time..
Write a program that will offer 4 option 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 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.


Positional & Keyword Arguments
When calling a function, you may need to pass arguments to parameters.
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
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
..Thinking Time..
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,
invokes this function to return the index of the smallest element, and
displays the index.
Recursive function
Recursive module: A module that calls itself
Example 1: Factorial Without Recursive
N i Product Display Factorial

5 - 1 - -

1 1 1 -

2 2 2 -

3 6 6 -

4 24 24 -

Output: 5 120 120 -

120
Recursive function (cont..)
Example 1: Factorial With Recursive
Output:
Recursive function (cont..)
N=5
Output:
Factorial(5) 120

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: Factorial Without Recursive
Output:
Recursive function (cont..)
Example 2: Factorial 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
..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: You may reuse the function factorial in our class example.
Possible Solutions

Output:
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..)
Example:

Output:
Summary
Making program modular and reusable is one of the central goals in software engineering.
Functions help to achieve this goal.
A function header begins with the def keyword followed by function’s name and
parameters, and ends with a colon. Parameters are optional.
A function is called a void or None function if it does not return a value.
A return statement can also be used in a void function for terminating the function and
returning to the function’s caller. Python return statement can return multiple values.
A function’s arguments can be passed as positional arguments or keyword arguments.
When you invoke a function with a parameter, the argument is pass-by-value.
A variable created in a function is called local variable. Global variables is created outside
all functions and are accessible to all functions in their scope.
Python accepts recursive function which means a defined function can call itself.
Nested functions occur when another function is declared in a function.

You might also like