0% found this document useful (0 votes)
34 views18 pages

Econtent of Functions Chapter of Python Xii

class 12 functions enotes

Uploaded by

joshilavanya11
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)
34 views18 pages

Econtent of Functions Chapter of Python Xii

class 12 functions enotes

Uploaded by

joshilavanya11
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/ 18

Date : 28-03-24

E-CONTENT-1
XII-Science
Subject : Computer Science Python
Chapter : 1 “Functions”
Introduction:-
Large programs are generally avoided because it becomes difficult to
manage it. So in order to simplify the work we divide the large code
into smaller units known as functions.
A function is a named unit of group of statements which can be
invoked/called from other parts of the program.
Benefits of using Functions:-
➔ Program handling becomes easier.
➔ Avoid ambiguity.
➔ Reduce the program size.
➔ program becomes more readable & understandable.
Example showing defining of a function:-
def Interest(P,R,T):
SI=(P*R*T)/100
return SI

In the above example of function definition ,


➔ def is the keyword which signifies that function definition is
starting.
➔ identifier following the def keyword is the name of the function.
i.e. Interest in our above example.
➔ The variables inside the parenthesis are called arguments or
parameters i.e. P,R, and T are arguments.

Page | 1
➔ the colon (:) at the end of the function line signifies that it is a
block.
➔ The statements written inside the block of the function are
automatically indented as they signifies that these statements
are the body of the function.
➔ The return statement returns the computed result.

The non-indented statements written outside the function body are


not considered to be the part of the function.
Calling/Invoking of a function:-
In order to use the function which has been defined , there is need to
call/invoke the function. For this proper function call statement has
to be written for example :-
<function_name>(list of arguments)
or
<function_name>( ) // no arguments passed.
As already we have defined the function Interest above so we can call
the function by using the following statement:
Interest(P,R,T)
or
Interest(1000,3,2)
# Various ways to invoke the function:-
1. Passing literal as argument in function call:
e.g. cube(5)

2. Passing variable as argument in function call


e.g. x=10
cube(x)

Page | 2
3. taking input from the user and passing the input as argument in
function call.
x=int(input(“enter the value of x: “))
cube(x)

4. using function call inside another statement:


print(cube(3))
first function cube will be called and the returned computed
result will get print

5. Using function call inside an expression


x=3*cube(4)
The computed result of function cube(4) will get multiplied by 3.
Note:
While calling the function only name of function and arguments
are given. No use of keyword def and colon is allowed.
Python Function types:-
➢ Built in function
➢ Function defined in modules.
➢ User defined functions

DEFINING FUNCTIONS IN PYTHON:-


Various components of function definitions are :-
1. Function header:-
◼ first line of function definition.
◼ begins with def keyword.
◼ terminates with colon(:)
◼ contains name of function
◼ list of parameters ( optional)

Page | 3
2. Parameters:-
◼ Variables passed inside the parenthesis.

3. Function Body:
◼ refers to indented block of statements.
◼ body may or may not have return value.

4. Indentation:-
◼ The blank space in the beginning of a statement within the block.

STRUCTURE OF PYTHON PROGRAM:-


◼ Function definitions are given at the top followed by non function
statements.
◼ The statements which are not the part of function of body are not
indented.
◼ Such statements are the top level statements.
◼ Are the part of main program.
◼ Execution starts from top level statements.
◼ Python gives special name _main_
◼ Python stores this name in built in variable _name_.
example:-
def function1( ):
-----------
-----------
def function2( ):
-----------
-----------

# top level statements


statement1
Page | 4
statement2
# What is Flow of execution?
The flow of execution refers to order in which statements are
executed during the program run.
A block is executed in execution frame which contains:-
◼ some internal information
◼ name of function
◼ values passed to the function
◼ variables created within the function.
◼ information about the next instruction.

As function is called , following method takes place:-


(a) execution frame of function is created.
(b) control is transferred to it.
(c) within the frame , statements are executed.
(d) with use of return statement control shifts back to the statement
from where function was called/invoked.

ARGUMENTS & PARAMETERS:-


◼ Python refers to the values being passed as arguments.
◼ Python refers to the values being received as parameters.
◼ Arguments appear in function call statement.
◼ Parameters appears in function header.
◼ Arguments can be of any one of the following types:-
(a) literals
(b) variables
(c) expressions
◼ Parameters can be only of variable type.
◼ The word “argument” refers to Actual Argument.
◼ The word “parameters” refers to Formal Parameter.

Page | 5
PASSING PARAMETERS:-
Python supports 3 types of formal parameters:-
1. POSITIONAL/REQUIRED ARGUMENTS:-
When the function call statement must match the number and
order of the arguments as defined in the function definition, this
is called Positional arguments. Such arguments are also called
mandatory arguments as no value can be skipped from the
function call and we cannot change the order.
example:-
Consider the function block:
def func1(a,b,c):
-----------
-----------
-----------

func1(x,y,z) // function call 1


func2(2,x,y) // function call 2
func3(3,5,6) // function call 3

In the first function call a will get value of x , b will get value of y
and c will get value of z.

Note :-
The number of arguments passed has matched with the
number of parameters received.
Moreover values are given position or order wise i.e. first
parameter receives value of first argument , 2nd parameter will
receive value of 2md argument so on.

2. DEFAULT ARGUMENTS:-
A parameter having default value in the function header is known as
default parameter.
Python allows the user to assign default values to the function
parameters which is useful in the case matching argument is not
passed in the function call statement.
Page | 6
example:
def interest(p,t,r=0.8):
In the above example 0.8 is the default value of parameter r i.e. rate.
If user does not provide value of r in function call then Python will
fill the missing value with this default value
Now the function interest is called/invoked as per the following
statement:
interest(2000,3)
Value 2000 is provided to p i.e. principle , 3 is passed to parameter t
i.e. time , the third parameter ‘r’ is missing in function call so it will
take the default value 0.10 given in function header.

Note:
In the function header any parameter cannot have the default value
unless all parameters appearing on its right side have their default
values.

Note:-
The required parameter should be used before default parameters.
examples:-
def interest(p=1000,t=3,r=0.8): // valid
def interest(p,t=2,r):

// invalid
( as default parameter cannot be used before required parameter)

def interest(p,t,r=0.5): // valid

3. KEYWORD ARGUMENT:-
The default arguments give you the flexibility to specify the default
value so that it can be skipped from the function call. But we cannot
change the order of the arguments in the calling statement.
So in order to have complete control & flexibility over the arguments
Python provides keyword arguments.

Page | 7
With the help of keyword arguments user can write any argument
in any order provided we provide the name to the argument.
Keyword arguments are also called named argument.
example:
interest(prin=2000,time=2,rate=0.04)
interest(time=3,prin=2000,rate=0.03)
Both the above function calls are valid even if the order of
argument does not match with order of parameters.
Rules for combining all three types of arguments:-
◼ an argument list must contain first positional arguments followed
by keyword arguments.
◼ keyword arguments should be taken from required arguments
only.
◼ Do not specify a value for an argument more than once.

RETURNING VALUES FROM THE FUNCTIONS:-


Functions in python may or may not return a value, so there are two
categories of functions in python.
(a) Functions returning some value ( non void functions)
(b) Functions not returning any value.(void function)

(a) Function returning some value (non void function)


The functions that return the computed result in terms of value fall
in this category. The computed value is returned using the return
statement.
The value being returned can be either:
(a) literal
(b) or a variable
(c) or an expression
example:

Page | 8
return r
return 45
return a+b
Note :
Functions returning the value are also called Fruitful functions.
Note:
The return statement ends the function execution even if it is middle
of the function i.e. the function ends the moment it reaches the return
statement or all the statements in the function body have been
executed.
example:
def check(a):
a=math.fabs(a)
return a
print(a)
// this print statement will not get execute due to the use of return
statement before it as return will end up the function execution
check(-15)
(b) Functions not returning any value ( void functions)
The functions which performs some work but does not return back
any computed value back to the caller part is called void functions
or Non fruitful Functions
A void function may or may not have return statement , if it has it will
be of the form
return
example:
def func( ):
print(“welcome to python”)
return
Page | 9
The void functions do not return any value but they return a
legal empty value of python i.e. None.
Every void function return value None to its caller.
example:
def greet( ):
print(“hello”)
a=greet( )
print(a)
output will be
hello
None

Returning Multiple Values:-


In order to return the multiple values from the function following
points to be undertaken:
1. The return statement inside the function should be of form:
return <value1/variable1/expression1> , <value2/variable2/exp2>
2. The function call statement should receive the values in any of the
following ways:
(a) Either the returned values are received in form of tuple:
def square(x,y,z):
return x*x,y*y,z*z
t=square(2,3,4)
print(t)
(b) directly unpack the received values of tuple by specifying the
required number of variables on the left hand side
v1,v2,v3=square(2,3,4)
print(v1,v2,v3)
Page | 10
SCOPE OF VARIABLES:
The scope rules of the language are the rules that decide in which
part of the program a particular piece of code would be known and
accessed.
Global scope:
A name declared in top level statement i.e. _main_ part of the program
is said to have global scope. A global variable can be used in any
block/function in the whole program.
Local Scope:
A variable declared in function body is said to have local scope i.e. it
can only be used inside the function block.
Lifetime of the Variable
The lifetime of the variable is the time for which variable lives in the
memory. For a global variable the lifetime is the program run and for
the local variable lifetime is the function run.

NAME RESOLUTION:
Whenever we access any variable from within the program or function
python follows the name resolution rule. which is known as LEGB
rule. Python does the following:
1. it checks within the Local Environment, if it has the variable
then Python uses its value, otherwise move to next stage.
2. Python now checks in Enclosing Environment , if it finds the
variable then it uses it otherwise move to the next stage.
3. Python now checks the Global Environment , if it finds the
variable it uses its value otherwise move to the next stage.
4. Python checks in Built in environment , if variable is there
Python uses it , otherwise python indicates an error.

Page | 11
# Use of Global Variable inside Local Scope:
Local variable created with the same name as that of global variable
will hide the global variable. Suppose you want to assign value to the
global variable without creating any local variable or if you assign any
value to the name, Python will create the local variable with that name
, so to avoid such problems Python provides the ‘global’ keyword.
In order to tell the function that for a particular name do not create a
local variable rather use it as global variable user needs to write :
global <variable_name>
example:
def state1( ):
global tigers // it will use global variable tigers
tigers=15
print(tigers)
tigers=95
print(tigers)
state1( )
print(tigers)

Output:-
95
15
15

#Mutability & immutability properties of Passed Objects:-


Python variables are not storage containers rather they are memory
references as they refer to the memory address where value is entered.

Page | 12
Depending upon the mutable or immutable property of its data type
a variable behaves differently i.e.
(a) if the variable is immutable then any change in its value will
also change the memory address it is referencing too.
(b) if the variable is mutable then any change in the value of
variable will not change its memory address.
Example showing passing an immutable type value to the
function:-
def f1(a):
print(“value of a” ,a)
a=a+2
print(“Value of a now changes to” a)
_main_
num=3
print(“calling function with variable num having value”,num)
f1(num)
print(Back from function f1 num is :” ,num)

Output:-
calling function with variable num having value 3
value of a 3
value of a now changes to 8
Back from function f1 num is 3

Conclusion:-
The function f1( ) receives the parameter ‘a’ and then changes its value
by expression a=a+3 , but the changed value does not reflect the
original variable ‘num’ when the control returns back to the _main_
part
Page | 13
Example showing passing an Mutable type value to the function:-
def f1(L):
print(“List Received” ,L)
L[0]+=2
print(“List after changes :”,L)
_main_
List=[1]
print(“List before function call:”,List)
f1(List)
print(List after function call:” ,List)

Output:-
List before function call [1]
List received [1]
List after changes [3]
List after function call [3]

Conclusion:-
The function f1( ) receives the list ‘L’ which is a mutable type and
then changes its value by expression L[0]+=2 , and the changed value
is reflected in the original list List passed when the control returns
back to the _main_ part.

Page | 14
PRACTISE QUESTIONS BASED ON FUNCTIONS:-
1. Give the output of the code:-
def change(m,n):
for i in range(n):
if m[i]%5==0:
m[i]//=5
if m[i]%3==0:
m[i]//=3
L=[25,8,75,12]
change(L,4)
for i in L:
print(i,end= ‘#’)

2. Give the output of the code:


def update(x=10):
x+=15
print(“x”,x)
x=20
update( )
print(“x”,x)

3. Give the output of the following code:-


def addEm(x,y,z):
print(x+y+z)
def prod(x,y,z):
return x*y*z
a=addEm(6,16,26)
b=prod(2,3,6)
print(a,b)
Page | 15
4. Give the output of the code:
a=10
def cal( ):
global a
a=15
b=20
print(a)
call( )

5. Give the output of the code:


def check(n1=2,n2=2):
n1=n1+n2
n2+=1
print(n1,n2)
check( )
check(2,1)
check(3)

# Programs based on functions concept:


1. To display table of a number:
def table(num):
for i in range(1,11):
print(num, “x” , i , “=”,num*i)
n=int(input(“Enter the number :=”))
table(n)

Page | 16
2. To check if number is palindrome
def palin(num):
n=num
rev=0
while n!=0:
d=n%10
rev=(rev*10)+d
n//=10
print(rev)
if rev==num:
print(“Number is Palindrome”)
else:
print(“Number is not Palindrome”)

n=int(input(“Enter the number:=”))


palin(n)

3. To display reverse of the number


def Reverse(num):
n=num
rev=0
while n!=0:
d=n%10
rev=(rev*10)+d
n//=10
print(rev)
n=int(input(“Enter the number:=”))
Reverse(n)

Page | 17
List based programs using functions:
To double the element of list if it is even , otherwise convert iinto
its half
def Change(L):
x=len(L)
for i in range(x):
if L[i]%2==0:
L[i]=L[i]*2
else:
L[i]=L[i]//2
print(L)

To find sum of List elements:


def Change(L):
x=len(L)
for i in range(x):
s=s+L[i]
print(“sum=”,s)

TYPES OF FUNCTIONS:-
(a) Built in Functions:
These are the functions which are predefined in Python and
are always available for use. e.g. len(),float(),id(),type()

(b) Functions defined inside module:


These are the functions which are inbuilt or predefined inside
particular module. If user want to use these functions then
the corresponding module has to be imported first.
e.g. sqrt(),pow() are inbuilt in math module.

(c) User defined functions:


These are the functions which are not predefined or inbuilt
in any module rather they are created/defined by user
himself. e.g. Value(),Func(),Interest()

Page | 18

You might also like