list
list
list
CBSE Syllabus
Functions: scope, parameter passing, mutable/immutable
properties of data objects, pass
arrays to functions, return values
What are User Defined Functions
(UDF)
■ Name of a code at a separate place is called a User
Defined Function
■ Example factorial(), hcf(), Fibonacci() etc
■ A programming Language that supports UDF is called a
modular language
■ User-defined functions help to decompose a large program
into small segments which makes program easy to
understand, maintain and debug.
■ If repeated code occurs in a program. Function can be
used to include those codes and execute when needed by
calling that function.
■ Promotes reusability
Syntax
#Function definition
def factorial(n): #n is a formal argument
#Statement 1
f=1
for i in range(1,n+1):
f=f*i
return f #Statement 2
#return breaks the control of the function and returns the value to the
calling function
num1 = 6
print(factorial(num1)) #Statement 3 (actual
arguments) and function
call
Fruitful and void functions
Example
def printpattern(n):
for i in range(1,n+1):
print(“*”*i)
printpattern(5)
Importance of return keyword
■ return breaks the control from the UDF
Example 1
def function():
print(10)
print(30)
return
print(40)
function()
Importance of return keyword
■ return breaks the control from the UDF
Example 2
def function(n):
for i in range(n,10):
return i
print(function(4))
#The expected output here will be all numbers from 4 to 10 but it is
actually only 4 since return causes the function to break
To do
def power(m,n):
p=1
for i in range(______________): #1
_________p=p*i__________ #2 Assign power to p
return(p)_____________ #3 return the value of p to the calling
function
m=int(input(“Enter the value of m”))
n=int(input(“Enter the value of n”))
print(power(m,n__________________) #4 Call the function
Defining multiple functions
def hcf(m,n): #Function 1
while(m%n):
r=m%n #r=5
m=n #m=10
n=r #n=5
return n
print(hcf(25,15))
Session 2
User
Defined
Functions
Recap of last class
■ What is a UDF
■ Syntax
■ Fruitful and void Functions
■ Formal and Actual Arguments
■ Function call and Function definition
■ Importance of return keyword
■ How to handle multiple functions
■ Return multiple values
Returning Multiple values
■ Python allows return multiple items using tuples or sequential data types
Example
def pickthreelarge(l):
a=max(l)
l.remove(a)
b=max(l)
l.remove(b)
c=max(l)
l.remove(c)
return(a,b,c)
L=[45,33,1,15,99,18,60,20,45]
print(pickthreelarge(L))
Function overloading
■ Python treats functions as objects
■ Like an object can be redefined so can a function
■ Example
def function(a,b):
return a+b
def function(a):
return a*10
def function(a,b,c):
return a+b+c
function(10) #will raise error
function(10,20) # will raise error
print(function(10,20,30)) #valid function call
HW
1) Write a program to input a number and then call the functions count(n) which returns the number of
digits
reverse(n) which returns the reverse of a number
hasdigit(n) which returns True if the number has a digit else False show(n) to show the number as sum of
place values of the digits of the number.
(eg 124 = 100 + 20 + 4)
XII Computer
Science
Session 3
User Defined
Functions
Recap
def armstrong(n):
#To find armstring between range
def checkarmstrong(n):
# print all Armstrong numbers from 1 to n
checkarmstrong(300)
Types of Arguments
■Positional Arguments
■Default Arguments
■Named Arguments
Positional Arguments
■ Arguments sent to a function in correct positional order
Example
def function(a,b,c):
return (a+b-c)
function(10,20,5)
■ Here the value of a is assigned value 10
■ b is assigned value 20
■ And c is assigned value 5
Default Arguments
■ Default values indicate that the function argument will
take that value if no argument value is passed during
function call.
■ The default value is assigned by using assignment (=)
operator.
Example
def power(m,n=1):
p=1
for i in range(n):
p=p*I
return p
print(power(10,3))
Default Arguments
■ Default Arguments can only be created from right to left
order
Session 4
User Defined
Functions
Quick recap
■ If return statement is not used inside the function, the function
will return:
def FMA(x,y):
z=multiply(x,y)
x=x+z
return x
def multiply(x,z):
x=x*z
return x
z=FMA(2,3)
print(z)
Named/Keyword Arguments
Python provides a method to change the position of the
arguments by giving Named Arguments
Example
def function(a,b,c):
print(a,b,c)
function(b=10,c=2,a=15)
print( a(‘m’))
print( a('m', 'j'))
print(a(q=‘b’,p=‘s’,s=‘z’))
print( a('m', ‘j’, q = 'a’))
print(a(s=‘l’,q=‘new’,p=‘great’))
Rules for combining all three
arguments
• An argument list must contain positional arguments
followed by any keyword argument.
OR
• Keyword arguments must appear after all non
keyword arguments
1) fun1("Emma", age=23)
2) fun1(age =23,
name="Emma")
3) fun1(name=”Emma”, 23)
4) fun1(age =23, “Emma”)
Quick recap
■ Which of the following would result in an error?
■ def function1(var1=2, var2):
var3=var1+var2
return var3
function1(3)
■ def function1(var1, var2):
var3=var1+var2
return var3
function1(var1=2,var2=3)
■
def function1(var1, var2):
var3=var1+var2
return var3
function1(var2=2,var1=3)
■ def function1(var1, var2=5):
var3=var1+var2
return var3
function1(2,3)
Practical Question 8
A Number is a perfect number if the sum of all the factors of
the number (including 1) excluding itself is equal to number.
For example: 6 = 1+2+3 and 28=1+2+4+7+14
Number is a prime number if it 's factors are 1 and itself.
Write functions i) Generatefactors() to populate a list of
factors
ii) isPrimeNo() to check whether the number is prime number
or not
iii) isPerfectNo() to check whether the number is perfect
number or not
Session 5
User Defined
Functions
Learning Outcomes
Rules
■ Time for each question 1 min
■ 5 points to those who answer the correct answer first
■ 2 points to anyone who gives the correct answer there on
till time
■ those who do not answer 0 OBVIOUSLY
Quiz of the day
func(3, 7)
func(25, c = 24)
func(c = 50, a = 100)
Quiz of the day (Answer)
def isperfect(n):
s=0
for i in range(1,n//2+1):
if(n%i==0):
s+=i
return s==n
def findperfectinlist(l):
c=0
for i in l:
if(isperfect(i)):
print(i,end=' ‘)
c+=1
return("\nTotal no of perfect
numbers are "+str(c))
l=[12,6,4,2,18,32,28,125]
print(findperfectinlist(l))
Changing the sequence in a
function
UDF to swap adjacent numbers in a list
def remove(l):
pass
L= [6,5,3,1,9,14]
remove(L)
print(L)
Scope of a variable
Local Scope
Global Scope
XII Computer
Science
Session 6
User Defined
Functions
Learning Outcomes
We will understand
Will solve CBSE Programming questions of
Sequences in UDF
■ 414141
■ DROND#
■ GIRlRAJ#
■ 131313
■ ZARA#
Solution
def display(l):
for i in l:
if i.isdigit():
print(i*3)
else:
print(i+'#')
CBSE Question
■ Write definition of a method
MSEARCH(STATES) to display all the state
names from a list of STATES, which are
starting with alphabet M.
■ For example :
■ If the list STATES
contains["MP","UP","WB","TN","MH","MZ","
DL","BH","RJ","HR"]
■ The following should get displayed :
■ MP
■ MH
Solution
def msearch(states):
for i in states:
if
i.startswith('M’):
print(i)
Scope of a variable means the section of the code where the variable is visible
Global Scope
Local Scope
A variable created
inside a function def myfunc():
belongs to the local x = 300
scope of that print(x)
function, and can
only be used inside myfunc()
that function.
Their scope is only inside the function they are
created
They retain their life only till the function is getting
executed
Important
characteristi
cs of local
def function():
variables a=100
print(a)
a+=100
function()
print(a)
function()
def function():
a=100
print(a)
a+=100
def f2():
a=20
print(a)
Example function()
f2()
2 of local def function():
variables a=100
print(a)
a+=100
def f2():
a=20
print(a)
function()
f2()
a=50
print(a)
■ A variable defined outside is called a global
variable
■ A global variable has a global scope …..
Means any function can access it
■ A global variable lives its life till the program
Global executes
Variables
a=5
def function():
print(a)
function()
a=a+8
function()
XII Computer
Science
Session 7
User
Defined
Functions
Learning Outcomes
local to •b=20
the •swap(a,b)
•print(a,b)
function
Call by
Reference
Only
changes •def increase(l1): #l1=l
made to • for i in range(len(l1)):
• l1[i]+=i
mutable •l=[2,4,5,7,10,12]
datatypes •increase(l)
reflects •print(l)
back
def createDictionary(d):
Only #Lets begin the code of
changes finding frequency
for i in l:
made to if i not in d:
d[i]=1
mutable else:
datatypes d={}
d[i]+=1
reflects l=[6,3,3,1,2,3,6,9,1,1,3]
createDictionary(d)
back print(d)
Changi
ng a=10
edit
global def f():
variables global s
print(s)
in the s = "Python has extensive library
function support"
print(s)
Question answer_list = []
2 function(answer_list)
print(answer_list)
print(len(answer_list))
a=10
b=20
def change():
Question m=[9]
4 change(m)
print("m",m)
change()
print("m",m)
def f(p, q, r):
global s
p = 10
q = 20
Recap r = 30
s = 40
Question print(p,q,r,s)
5 p,q,r,s = 1,2,3,4
f(5,10,15)
print(p,q,r,s)
XII Computer
Science
Session 8
User
Defined
Functions
Recap Question 1
x = 50
def fun1():
# your code to assign x=20
fun1()
print(x) # it should print 20
def foo(x, y):
global a
a = 42
x,y = y,x
Recap b = 33
Question b = 17
c = 100
2 print(a,b,x,y)
a, b, x, y = 1, 15, 3,4
foo(17, 4)
print(a, b, x, y)
Recap Question 3
a=9,10
def g():
global a
a=a+(4,5)
def h():
a=(4,5)
h()
print(a)
g()
print(a)
Nested Functions
■ A function can contain function inside it.
■ It is the local function.
■ It is only callable from the function inside which it is
created
a=10
def outer():
a=15
def inner():
print(a) #local variable of outer
LEGB 15
inner()
outer()
print(a) #10
a=10
Nested def outer():
a=15
function def inner():
s to global a
print(a)
access inner()
global outer()
variables print(a)
a=10
def outer():
Nested a=15
functions def inner():
to access nonlocal a
print(a)
variables inner()
of outer outer()
function print(a)
def outer():
a=10
Question def inner():
1 Output a+=15
of the print(a)
code inner()
print(a)
outer()
val = 0
def f1():
val = 5
def f2():
Session 9
User
Defined
Functions
Let’s Revise
l=[14,5,2]
a=l[0]
def outer():
l.append('a') 3
a=5 [14, 5, 2, 'a', 3] 5
def inner(): [14, 5, 2, 'a', 3] 14
a=3
l.append(a)
def inneragain():
nonlocal a
l.append(a)
a=l.pop()
inneragain()
print(a)
inner()
print(l,a)
outer()
print(l,a)
Let’s revise
a='new'
def outer(a):
a=a+'year'
def inner1():
global a newyear
a=a+'days'
newyearhappy
def inner2():
nonlocal a newdays
a=a+'happy'
inner1()
print(a)
inner2()
print(a)
outer(a)
print(a)
x=15
Let’s revise def function():
x=2
global inner
print(x)
def inner():
global x
x=5
def f1():
x=10 10
def inner(): 13
nonlocal x
x=x+3 2
print(x) 5
print(x)
inner()
f1()
function()
inner()
print(x)
•Every value is associated to a variable
•Namespace is a dictionary of Names
Namespa
ce
•Example
•a=10
Namespac •b=20
e •c=30
•Namespace will be
{a:10,b:20,c=30}
a_var = 5
b_var = 7
a=10
def phone():
global variables
b=50 ‘a’:10
print("b",globals()) ‘phone’:{‘function phone’}
print("b",locals())
def inner(): Local variables
c=20 ‘b’:50
nonlocal b c global variables
print("c ‘a’:10
global",globals())
print("c C local variables
‘c’:20
local",locals()) ‘b’:50
inner()
phone()
LEGB Rule
•are listed below in terms of hieraIn
Python, the LEGB rule is used to decide
the order in which the namespaces are to
be searched for scope resolution.