Computer Science
Functions
Visit : python.mykvs.in for regular updates
WARM UP ACTIVITY
1. 1. Take out a piece of paper and a pencil.
2. Tell them to select an everyday task from the list and order
the steps for that task.
3. Discuss your students' sequencing lists and expected
outcomes.
4. Explain that functions are usually used when the same
instructions must be repeated or when the same sequence
of instructions must manipulate different inputs, which we
will explore in today's lesson.
PREVIOUS KNOWLEDGE
Which Keyword is used for declaring
a function?
Advantages of using functions
OPENING ACTIVITY
def greatest ( List ) : What is the link between
max = List[0]
for val in List[1:] : PARAGRAPH and PYTHON PROGRAM.
if val > max : max = val
return max
eval(input("Ent
greatest(a)
Programs are like a big article. It contains hundreds of
statements. So we will break it into small pieces called
functions ( Paragraph of Statements ).We can learn more
about it in the 4th chapter PYTHON LIBRARIES.
Why Function is needed ?
Learning Objective
Specific Learning Objectives:
• To understand the significance of Functions.
• To have an understanding about flow of execution of a program where
functions have been used.
• To have an understanding about environments created by Python
interpreter.
• Students will be able to write and understanding function defintion
and call statement.
• To understand the idea of Python library, module and mathematical
functions, string functions.
FUNCTION TAKES
DATA, AND WILL
PRODUCE DESIRED
OUTPUT
i o n
DATA
fu nc t
e s the
h a t do
W
do?
OUTPUT
Assume any value in x and
calculate polynomial 2x2
= 2x 2
For x = 1, the result is 2 * 12 = 2
For x = 2 , the result is 2 * 22 = 8
For x = 3, the result is 2 * 32 = 18
Passing the value 1 to x
and Returns 22 * Click
1 ** 1here
= 2 to watch
FUNCTION TAKES DATA
Passing the value 2 to x
and Returns 82 * Click
2 ** 2here
= 8 to watch
PRODUCE OUTPUT Passing the value 3 to x
and Returns 18 Click
2 * 3 ** 3 =here
18 to watch
Function Introduction
A function is a programming block of codes which
is used to perform a single, related task. It only
runs when it is called. We can pass data, known
as parameters, into a function. A function can
return data as a result.
We have already used some python built in
functions like print(),etc.But we can also create
our own functions. These functions are
called user-defined functions.
Visit : python.mykvs.in for regular updates
Advantages of Using functions:
1.Program development made easy and fast : Work can be divided among
project members thus implementation can be completed fast.
2. Program testing becomes easy : Easy to locate and isolate a faulty function
for further investigation
3.Code sharing becomes possible : A function may be used later by many
other programs this means that a python programmer can use function written by
others, instead of starting over from scratch.
4.Code re-usability increases : A function can be used to keep away from
rewriting the same block of codes which we are going use two or more locations in
a program. This is especially useful if the code involved is long or complicated.
5.Increases program readability : It makes possible top down modular
programming. In this style of programming, the high level logic of the overall
problem is solved first while the details of each lower level functions is addressed
later. The length of the source program can be reduced by using functions at
appropriate places.
6.Function facilitates procedural abstraction : Once a function is written,
it serves as a black box. All that a programmer would have to know to invoke a
function would be to know its name, and the parameters that it expects
7.Functions facilitate the factoring of code : A function can be called in
other function and so on…
Visit : python.mykvs.in for regular updates
MAIN ACTIVITY
EXPLAIN FUNCTION USING REAL WORLD EXAMPLES
Create a function named MY_SCHOOL()
CREATE A FUNCTION AND PASS PARAMETERS & RETURN VALUE
Creating & calling a Function(user defined)
A function is defined using the def keyword
in python.E.g. program is given below.
def my_own_function():
#Function block/
print("Hello from a function") definition/creation
#program start here.program code
print("hello before calling a function")
my_own_function() #function calling.now function codes will be executed
print("hello after calling a function")
Save the above source code in python file and
execute it
Visit : python.mykvs.in for regular updates
ARGUMENTS OR PARAMETERS
The values passed to a function are called
arguments or Parameters.
arguments
Arguments act as an input to
the function, to carry out
the specified task.
Function Definition Returns output
Variable’s Scope in function
There are three types of variables with the view of scope.
1. Local variable – accessible only inside the functional block where it is declared.
2. Global variable – variable which is accessible among whole program using
global keyword.
3. Non local variable – accessible in nesting of functions,using nonlocal
keyword.
Local variable program: Global variable program:
def fun(): def fun():
s = "I love India!" #local variable global s #accessing/making global variable for fun()
print(s) print(s)
s = "I love India!“ #changing global variable’s value
s = "I love World!" print(s)
fun()
print(s) s = "I love world!"
fun()
Output: print(s)
I love India! Output:
I love World! I love world!
I love India!
I love India!
Visit : python.mykvs.in for regular updates
Variable’s Scope in function
#Find the output of below program
def fun(x, y): # argument /parameter x and y
global a
a = 10
x,y = y,x b
= 20
b = 30
c = 30
print(a,b,x
,y)
a, b, x, y =
1, 2, 3,4
fun(50, 100) #passing value 50 and 100 in parameter x and y of function fun()
print(a, b, x, y)
Visit : python.mykvs.in for regular updates
Variable’s Scope in function
#Find the output of below program
def fun(x, y): # argument /parameter x and y
global a
a = 10
x,y = y,x b
= 20
b = 30
c = 30
print(a,b,x
,y)
a, b, x, y =
1, 2, 3,4
fun(50, 100) #passing value 50 and 100 in parameter x and y of function fun()
print(a, b, x, y)
OUTPUT :-
10 30 100 50
10 2 3 4
Visit : python.mykvs.in for regular updates
Variable’s Scope in function
Global variables in nested function
def fun1():
x = 100
def fun2():
global
x x =
200
print("Before calling fun2: " + str(x))
print("Calling fun2 now:")
fun2()
print("After calling fun2: " + str(x))
fun1()
print("x in main: " + str(x))
OUTPUT:
Before calling fun2: 100
Calling fun2 now:
After calling fun2: 100
x in main: 200
Visit : python.mykvs.in for regular updates
Variable’s Scope in function
Non local variable
def fun1():
x = 100
def fun2():
nonlocal x #change it to global or remove this declaration
x = 200
print("Before calling fun2: " + str(x))
print("Calling fun2 now:")
fun2()
print("After calling fun2: " + str(x))
x=50
fun1()
print("x in main: " + str(x))
OUTPUT:
Before calling fun2: 100
Calling fun2 now:
After calling fun2: 200
x in main: 50
Visit : python.mykvs.in for regular updates
Function
Parameters / Arguments
These are specified after the function name, inside the parentheses. Multiple
parameters are separated by comma.The following example has a function with
two parameters x and y. When the function is called, we pass two values, which
is used inside the function to sum up the values and store in z and then return
the result(z):
def sum(x,y): #x, y are formal
arguments z=x+y
return z #return the result
x,y=4,5
r=sum(x,y) #x, y are actual arguments
print(r)
Note :- 1. Function Prototype is of function with name
,argument
declarationand return type.
2. A formal parameter, i.e. a parameter, is in the function definition. An
actual parameter, i.e. an argument, is in a function call.
Visit : python.mykvs.in for regular updates
Function
Function Arguments
Functions can be called using following types of formal arguments −
• Required arguments - arguments passed to a function in correct positional order
• Keyword arguments - the caller identifies the arguments by the parameter name
• Default arguments - that assumes a default value if a value is not provided to argu.
• Variable-length arguments – pass multiple values with single argument name.
#Required arguments #Keyword arguments
def fun( name, age ):
def square(x): "This prints a passed info into this
z=x*x function"
return z print ("Name: ", name)
print ("Age ", age)
r=square() return;
print(r)
# Now you can call printinfo
#In above function square() we have to function fun( age=15,
definitely need to pass some value to name="mohak" )
argument x. # value 15 and mohak is being
passed to relevant argument based on
keyword used for them.
Visit : python.mykvs.in for regular updates
Function
#Default arguments #Variable length arguments
def sum(x=3,y=4): def sum( *vartuple ):
z=x+y s=0
return z for var in vartuple:
s=s+int(var)
r=sum() return s;
print(r)
r=sum(x=4) r=sum( 70, 60, 50 )
print(r) print(r)
r=sum(y=45) r=sum(4,5)
print(r) print(r)
#default value of x and y is being used #now the above function sum() can sum
when it is not passed n number of values
Visit : python.mykvs.in for regular updates
Lamda
Python Lambda
A lambda function is a small anonymous function which can take any number of
arguments, but can only have one expression.
E.g.
x = lambda a, b : a * b
print(x(5, 6))
OUTPUT:
30
Visit : python.mykvs.in for regular updates
Mutable/immutable properties of data objects w/r function
Everything in Python is an object,and every objects in Python can be
either mutable or immutable.
Since everything in Python is an Object, every variable holds an object
instance. When an object is initiated, it is assigned a unique object id. Its
type is defined at runtime and once set can never change, however its
state can be changed if it is mutable.
Means a mutable object can be changed after it is created, and
an immutable object can’t.
Mutable objects: list, dict, set, byte array
Immutable objects: int, float, complex, string, tuple, frozen set ,bytes
Visit : python.mykvs.in for regular updates
Mutable/immutable properties of data objects w/r function
How objects are passed to Functions
#Pass by reference #Pass by value
def updateList(list1): def updateNumber(n):
print(id(list1)) print(id(n))
list1 += [10] n += 10
print(id(list1)) print(id(n))
n = [50, 60] b=5
print(id(n)) print(id(b))
updateList(n) updateNumber
print(n) (b) print(b)
print(id(n)) print(id(b))
OUTPUT OUTPUT
34122928 1691040064
34122928 1691040064
34122928 1691040224
[50, 60, 10] 5
34122928 1691040064
#In above function list1 an object is being passed #In above function value of variable b is
and its contents are changing because it is not being changed because it is immutable
mutable that’s why it is behaving like pass by that’s why it is behaving like pass by value
reference
Visit : python.mykvs.in for regular updates
Pass arrays to functions
Arrays are popular in most programming languages like: Java, C/C++, JavaScript and
so on. However, in Python, they are not that common. When people talk about Python
arrays, more often than not, they are talking about Python lists. Array of numeric
values are supported in Python by the array module.
e.g.
def dosomething( thelist ):
for element in thelist:
print (element)
dosomething( ['1','2','3'] )
alist = ['red','green','blue']
dosomething( alist )
OUTPUT:
1
2
3
red
green
Blue
Note:- List is mutable datatype that’s why it treat as pass by reference.It is
already explained in topic Mutable/immutable properties of data objects w/r
function
Visit : python.mykvs.in for regular updates
Functions using libraries
Mathematical functions:
Mathematical functions are available under math module.To use
mathematical functions under this module, we have to import the
module using import math.
For e.g.
To use sqrt() function we have to write statements like given below.
import math
r=math.sqrt(4)
print(r)
OUTPUT :
2.0
Visit : python.mykvs.in for regular updates
Functions using libraries
Functions available in Python Math Module
Visit : python.mykvs.in for regular updates
Functions using libraries(System defined function)
String functions:
String functions are available in python standard module.These are always
availble to use.
For e.g. capitalize() function Converts the first character of string to upper
case.
s="i love programming"
r=s.capitalize()
print(r)
OUTPUT:
I love
programming
Visit : python.mykvs.in for regular updates
Functions using libraries
String functions:
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
Searches the string for a specified value and returns the position
find()
of where it was found
format() Formats specified values in a string
Searches the string for a specified value and returns the position
index()
of where it was found
Visit : python.mykvs.in for regular updates
Functions using libraries
String functions:
Method Description
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
partition() Returns a tuple where the string is parted into three parts
Visit : python.mykvs.in for regular updates
Functions using libraries
String functions:
Method Description
Returns a string where a specified value is replaced with a
replace()
specified value
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
Visit : python.mykvs.in for regular updates
POSITIONAL PARAMETERS
KEYWORD PARAMETERS
KEYWORD PARAMETERS
DEFAULT PARAMETERS
A default argument is an argument that assumes a default value if a
value is not provided in the function call for that argument.
Following example gives idea on default arguments, it would print
default age if it is not passed:
def printinfo( name, age = 35 ): “Test
function"
print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="miki" );
printinfo( name="miki" );
This would produce following result:
Name: miki Age 50 Name: miki Age 35
Critical thinking
What is the difference
between a parameter and
an argument?
DIFFERENTIATED ACTIVITIES
Inside a function
Execute a with two Let the function return
function parameters, print the x parameter x+ 5.
the first
named my_fun parameter.
ction.
Research Activity
Write a Python function to calculate the Write a Python function that accepts a
factorial of a number (a non-negative string and calculate the number of
integer). The function accepts the upper case letters and lower case
number as an argument letters.
Self Assessment
https://pynative.com/python-functions/