USER DEFINED FUNCTIONS 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 N=int(input(“Enter a no”)) print(factorial(N)) #Statement 4 Function call
Fruitful and void functions ■ A function that returns something is called a fruitful function ■ A function that does not return anything is called a void function ■ A function that does not return anything returns None 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)) def lcm(m,n): #Function 2 return(m*n/hcf(m,n)) def main(): #Function 3 m=int(input("Enter the value of m")) n=int(input("Enter the value of n")) print(lcm(m,n)) main()
XII Computer Science Session 2 User Defined Functions 17th March 2021
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 18th March 2021
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)) print(power(7))
Default Arguments ■ Default Arguments can only be created from right to left order Example : Valid default arguments def function(a,b,c=1) def function(a,b=5,c=2) def function(a=3,b=2,c=10) Invalid default arguments def function(a=1,b,c) def function(a=2,b=3,c) def function(a,b=10,c) NOTE: The Default Arguments can only be from right to left
SELF TEST FIND THE INVALID FUNCTION CALLS def interest(prin, time, rate=0.10): #1 def interest(prin, time=2, rate): #2 def interest(prin=2000, time=2, rate): #3 def interest(prin, time=2, rate=0.10): #4 def interest(prin=200, time=2, rate=0.10): #5
Find the output (CBSE Sample Paper 2019) def Change(P ,Q=30): P=P+Q Q=P-Q print( P,"#",Q) return (P) R=150 S=100 R=Change(R,S) print(R,"#",S) S=Change(S)
Find the Output (CBSE 2019) Find and write the output of the following Python code : 3 def Alter(P=15,Q=10): p=100, q =10 P=P*Q Q=P/Q print(P,'#’,Q) return Q A=100 B=200 A=Alter(A,B) print(A,"$",B) B=Alter(B) print(A,"$",B) A=Alter(A) 100 print(A,"$",B) 2000#100 100$200 2000#200 100$200 1000#100 100$200
XII Computer Science Session 4 User Defined Functions 23rd March 2021
Quick recap ■ If return statement is not used inside the function, the function will return: ■ Which of the following function headers is correct? A. def fun(a = 2, b = 3, c) B. def fun(a = 2, b, c = 3) C. def fun(a, b = 2, c = 3) D. def fun(a, b, c = 3, d) ■ What is the output of the add() function call def add(a,b): return a+5,b+5 x,y=3,2 result=add(x,y) print(result,type(result)) print(x,y)
Quick recap What will be the output of the following Python code? def function1(var1=5, var2=7): var2=9 var1=3 print (var1, " ", var2) function1(10,12)
Quick recap - Important What gets printed 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) IMPORTANT : The passed keyword name should match with the actual keyword name.
Difference between Default Arguments and Named Arguments Default Arguments Named Arguments Arguments are given default value in Function definition Arguments are given value in Function call Allows function call to have variable no of arguments Allows function call to change the position of arguments Example def function(a,b=10): pass function(20) Example def function(a,b): pass function(b=10,a=20)
Find the output def a(s, p =‘s’, q=‘r’ ): return s + p + q 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 • You cannot specify a value for an argument more than once
Rules for combining all three arguments def interest( prin, cc, time=2, rate=0.09): return prin * time * rate Function call statement Legal//Illegal Reason interest(prin=3000, cc=5) Legal Non-default values provided as named arguments. interest(rate=0.12, prin=5000, cc=4) legal Keyword arguments can be used in any order and for the argument skipped, there is a default value interest(rate=0.05, 5000, 3) Illegal Keyword argument before positional arguments. interest(5000, prin=300, cc=2) illegal Multiple values provided for prin interest(5000, principal=300, cc=2) Illegal Undefined named used(principal is not a parameter) Interest(500, time=2, rate=0.05) Illegal A required argument (cc) is missing.
Given the following function fun1() Please select all the correct function calls def fun1(name, age): print(name, age) 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 Save the above as a module perfect.py and use in the program main.py as a menu driven program.
XII Computer Science Session 5 User Defined Functions 26th March 2021
Learning Outcomes ■ Revise different type of parameters through an interaction q/a session ■ Understand how to pass different type of sequences to functions
QUIZ OF THE DAY 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 1) What will be the output of the following Python code? def func(a, b=5, c=10): print('a is', a, 'and b is', b, 'and c is', c) func(3, 7) func(25, c = 24) func(c = 50, a = 100)
Quiz of the day (Answer) 1) What will be the output of the following Python code? def func(a, b=5, c=10): print('a is', a, 'and b is', b, 'and c is', c) func(3, 7) func(25, c = 24) func(c = 50, a = 100) ANSWER a is 3 and b is 7 and c is 10 a is 25 and b is 5 and c is 24 a is 100 and b is 5 and c is 50
Quiz of the day 2) Name the invalid function calls def student(firstname, lastname ='Mark', standard ='Fifth'): print(firstname, lastname, 'studies in', standard, 'Standard') a)student() b) student(firstname ='John', 'Seventh’) c) student(subject ='Maths') d) student(firstname ='John’) e) student(firstname ='John', standard ='Seventh')
Quiz of the day (Answer) 2) Name the invalid function calls def student(firstname, lastname ='Mark', standard ='Fifth'): print(firstname, lastname, 'studies in', standard, 'Standard') a)student() #invalid because required argument is missing b) student(firstname ='John’, standard='Seventh’) #invalid non keyword argument after keyword argument c) student(subject ='Maths') #unknown keyword argument d) student(firstname ='John’) #valid e) student(firstname ='John', standard ='Seventh') #valid
Passing sequence to functions Any sequence can be passed as an argument to the function Example the below program counts number of 2 digit numbers in a program def function(l): c=1 for i in l: if(len(str(i))==2): c+=1 return c l=[2,12,232,15,6,19,24] print(function(l))
Passing sequence to functions – Mutable sequence – The function is supposed to calculate and return an answer – The function is supposed to make changes in the sequence
Example of sequence returning single answer UDF to find the number of perfect numbers from a list 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 swap(x): x=l #aliasing for i in range(0,len(l)-1,2): l[i],l[i+1]=l[i+1],l[i] #Statement to swap list l=[1,2,3,4,5,6] swap(l) print(l) NOTE: If you can making changes to a mutable datatype in a function. You do not need to return
Question Write a UDF to take a list and remove all even numbers from it def remove(l): pass L= [6,5,3,1,9,14] remove(L) print(L)
Scope of a variable Scope of a variable means the section of the code where the variable is visible A variable can have the following scopes in Python Local Scope Global Scope
XII Computer Science Session 6 User Defined Functions 31st March 2021
Learning Outcomes We will understand Will solve CBSE Programming questions of Sequences in UDF Will get acquainted with the Concept of scope and life Will be able to Categorize of variables in different scopes
Sequences practice To do Padlet link shared
CBSE Questions ■ Write a method in python to display the elements of list thrice if it is a number and display the element terminated with '#' if it is not a number. ■ For example, if the content of list is as follows: ■ List=['41','DROND','GIRIRAJ','13','ZARA’] ■ 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 ■ MZ
Solution def msearch(states): for i in states: if i.startswith('M’): print(i)
Scope of a variable Scope of a variable means the section of the code where the variable is visible A variable can have the following scopes in Python Local Scope Global Scope
Local Scope A variable created inside a function belongs to the local scope of that function, and can only be used inside that function. def myfunc(): x = 300 print(x) myfunc()
def function(): a=100 print(a) a+=100 function() print(a) function() Important characteristics of local variables Their scope is only inside the function they are created They retain their life only till the function is getting executed
def function(): a=100 print(a) a+=100 def f2(): a=20 print(a) function() f2() def function(): a=100 print(a) a+=100 def f2(): a=20 print(a) function() f2() a=50 print(a) Example 2 of local variables
a=5 def function(): print(a) function() a=a+8 function() Global Variables ■ 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 executes
XII Computer Science Session 7 User Defined Functions 5th April 2021
Learning Outcomes ■ We will be able to understand ■ Local and Global scope ■ global and nonlocal keyword ■ Namespace resolution ■ LEGB Rule
Formal Arguments are local to the function • def swap(a,b): • a,b=b,a • print(a,b) • a=10 • b=20 • swap(a,b) • print(a,b) Call by Value
Only changes made to mutable datatypes reflects back • def increase(l1): #l1=l • for i in range(len(l1)): • l1[i]+=i • l=[2,4,5,7,10,12] • increase(l) • print(l) Call by Reference
Only changes made to mutable datatypes reflects back def createDictionary(d): #Lets begin the code of finding frequency for i in l: if i not in d: d[i]=1 else: d[i]+=1 d={} l=[6,3,3,1,2,3,6,9,1,1,3] createDictionary(d) print(d)
Changing Global variables in UDF a=10 def function(): print(a) a=a+2 function()
def f(): global s print(s) s = "Python has extensive library support" print(s) s = "Python is a dynamic language" f() print(s) How to edit global variables in the function ■ We can tell Python that we need to edit the global variable by using the global keyword
Recap Question 1 • Differentiate between call by value and call by reference?
Recap Question 2 def function(bar): bar.append(42) bar.append([42]) answer_list = [] function(answer_list) print(answer_list) print(len(answer_list))
Recap Question 3 a=10 b=20 def change(): global a,b a=45 b=56 change() print(a) print(b)
Recap Question 4 def change(l=[]): l.insert(1,33) l.extend("new”) print("l”,l) m=[9] change(m) print("m",m) change() print("m",m)
Recap Question 5 def f(p, q, r): global s p = 10 q = 20 r = 30 s = 40 print(p,q,r,s) 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 8th April 2021
Recap Question 1 x = 50 def fun1(): # your code to assign x=20 fun1() print(x) # it should print 20
Recap Question 2 def foo(x, y): global a a = 42 x,y = y,x b = 33 b = 17 c = 100 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=10 def outer(): a=15 def inner(): print(a) #local variable of outer LEGB 15 inner() outer() print(a) #10 ■ A function can contain function inside it. ■ It is the local function. ■ It is only callable from the function inside which it is created
Nested functions to access global variables a=10 def outer(): a=15 def inner(): global a print(a) inner() outer() print(a)
Nested functions to access variables of outer function a=10 def outer(): a=15 def inner(): nonlocal a print(a) inner() outer() print(a)
Question 1 Output of the code def outer(): a=10 def inner(): a+=15 print(a) inner() print(a) outer()
Question 2 Output of the code val = 0 def f1(): val = 5 def f2(): val = 7.5; def f3(): nonlocal val; val = 10; print("f3:", val); f3(); print("f2:", val); f2(); print("f1:", val); f1();
Nested and Global functions can manipulate mutable datatypes without using global/local keyword x=[] def function(): x.append(4) print(x) function() print(x)
Nested and Global functions can manipulate mutable datatypes without using global/local keyword def outer(): a=[10] def inner(): a.append(15) print(a) inner() print(a) outer()
Nested and Global functions can manipulate mutable datatypes without using global/local keyword def outside(): d = {'outside': 1} def inside(): d['inside'] = 2 print(d) #d={‘outside’:1,’inside’:2} inside() print(d) #d={‘outside’:1,’inside’:2} outside()
XII Computer Science Session 9 User Defined Functions 9th April 2021
Let’s Revise l=[14,5,2] a=l[0] def outer(): l.append('a') a=5 def inner(): 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) 3 [14, 5, 2, 'a', 3] 5 [14, 5, 2, 'a', 3] 14
Let’s revise a='new' def outer(a): a=a+'year' def inner1(): global a a=a+'days' def inner2(): nonlocal a a=a+'happy' inner1() print(a) inner2() print(a) outer(a) print(a) newyear newyearhappy newdays
Let’s revise x=15 def function(): x=2 global inner print(x) def inner(): global x x=5 def f1(): x=10 def inner(): nonlocal x x=x+3 print(x) print(x) inner() f1() function() inner() print(x) 10 13 2 5
Namespace • Every value is associated to a variable • Namespace is a dictionary of Names
Namespace • Example • a=10 • b=20 • c=30 • Namespace will be {a:10,b:20,c=30}
Namespace Different type of Namespaces ■ Local ■ Enclosed ■ Global ■ Built in a_var = 5 b_var = 7 def outer_foo(): global a_var a_var = 3 b_var = 9 def inner_foo(): global a_var a_var = 4 b_var = 8 print('a_var inside inner_foo :', a_var) print('b_var inside inner_foo :', b_var) inner_foo() print('a_var inside outer_foo :', a_var) print('b_var inside outer_foo :', b_var) outer_foo() print('a_var outside all functions :', a_var) print('b_var outside all functions :', b_var)
Check local and global variables of a function a=10 def phone(): b=50 print("b",globals()) print("b",locals()) def inner(): c=20 nonlocal b print("c global",globals()) print("c local",locals()) inner() phone() global variables ‘a’:10 ‘phone’:{‘function phone’} Local variables ‘b’:50 c global variables ‘a’:10 C local variables ‘c’:20 ‘b’:50
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. • Local(L): Defined inside function/class • Enclosed(E): =Nonlocal Defined inside enclosing • functions(Nested function concept) • Global(G): Defined at the uppermost level • Built-in(B): Reserved names in Python builtin modules

USER DEFINED FUNCTIONS - PYTHON COMPUTER SCIENCE

  • 1.
    USER DEFINED FUNCTIONS CBSESyllabus ❖Functions: scope, parameter passing, mutable/immutable properties of data objects, pass ❖arrays to functions, return values
  • 2.
    What are UserDefined 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
  • 3.
    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 N=int(input(“Enter a no”)) print(factorial(N)) #Statement 4 Function call
  • 4.
    Fruitful and voidfunctions ■ A function that returns something is called a fruitful function ■ A function that does not return anything is called a void function ■ A function that does not return anything returns None Example def printpattern(n): for i in range(1,n+1): print(“*”*i) printpattern(5)
  • 5.
    Importance of returnkeyword ■ return breaks the control from the UDF Example 1 def function(): print(10) print(30) return print(40) function()
  • 6.
    Importance of returnkeyword ■ 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
  • 7.
    To do def power(m,n): p=1 fori 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
  • 8.
    Defining multiple functions defhcf(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)) def lcm(m,n): #Function 2 return(m*n/hcf(m,n)) def main(): #Function 3 m=int(input("Enter the value of m")) n=int(input("Enter the value of n")) print(lcm(m,n)) main()
  • 9.
    XII Computer Science Session 2 UserDefined Functions 17th March 2021
  • 10.
    Recap of lastclass ■ 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
  • 11.
    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))
  • 12.
    Function overloading ■ Pythontreats 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
  • 13.
    HW 1) Write aprogram 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)
  • 14.
    XII Computer Science Session3 User Defined Functions 18th March 2021
  • 15.
    Recap def armstrong(n): #To findarmstring between range def checkarmstrong(n): # print all Armstrong numbers from 1 to n checkarmstrong(300)
  • 16.
    Types of Arguments ■Positional Arguments ■ Default Arguments ■ Named Arguments
  • 17.
    Positional Arguments ■ Argumentssent 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
  • 18.
    Default Arguments ■ Defaultvalues 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)) print(power(7))
  • 19.
    Default Arguments ■ DefaultArguments can only be created from right to left order Example : Valid default arguments def function(a,b,c=1) def function(a,b=5,c=2) def function(a=3,b=2,c=10) Invalid default arguments def function(a=1,b,c) def function(a=2,b=3,c) def function(a,b=10,c) NOTE: The Default Arguments can only be from right to left
  • 20.
    SELF TEST FIND THEINVALID FUNCTION CALLS def interest(prin, time, rate=0.10): #1 def interest(prin, time=2, rate): #2 def interest(prin=2000, time=2, rate): #3 def interest(prin, time=2, rate=0.10): #4 def interest(prin=200, time=2, rate=0.10): #5
  • 21.
    Find the output(CBSE Sample Paper 2019) def Change(P ,Q=30): P=P+Q Q=P-Q print( P,"#",Q) return (P) R=150 S=100 R=Change(R,S) print(R,"#",S) S=Change(S)
  • 22.
    Find the Output(CBSE 2019) Find and write the output of the following Python code : 3 def Alter(P=15,Q=10): p=100, q =10 P=P*Q Q=P/Q print(P,'#’,Q) return Q A=100 B=200 A=Alter(A,B) print(A,"$",B) B=Alter(B) print(A,"$",B) A=Alter(A) 100 print(A,"$",B) 2000#100 100$200 2000#200 100$200 1000#100 100$200
  • 23.
    XII Computer Science Session4 User Defined Functions 23rd March 2021
  • 24.
    Quick recap ■ Ifreturn statement is not used inside the function, the function will return: ■ Which of the following function headers is correct? A. def fun(a = 2, b = 3, c) B. def fun(a = 2, b, c = 3) C. def fun(a, b = 2, c = 3) D. def fun(a, b, c = 3, d) ■ What is the output of the add() function call def add(a,b): return a+5,b+5 x,y=3,2 result=add(x,y) print(result,type(result)) print(x,y)
  • 25.
    Quick recap What willbe the output of the following Python code? def function1(var1=5, var2=7): var2=9 var1=3 print (var1, " ", var2) function1(10,12)
  • 26.
    Quick recap -Important What gets printed 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)
  • 27.
    Named/Keyword Arguments Python providesa 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) IMPORTANT : The passed keyword name should match with the actual keyword name.
  • 28.
    Difference between DefaultArguments and Named Arguments Default Arguments Named Arguments Arguments are given default value in Function definition Arguments are given value in Function call Allows function call to have variable no of arguments Allows function call to change the position of arguments Example def function(a,b=10): pass function(20) Example def function(a,b): pass function(b=10,a=20)
  • 29.
    Find the output defa(s, p =‘s’, q=‘r’ ): return s + p + q 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’))
  • 30.
    Rules for combiningall three arguments • An argument list must contain positional arguments followed by any keyword argument. OR • Keyword arguments must appear after all non keyword arguments • You cannot specify a value for an argument more than once
  • 31.
    Rules for combiningall three arguments def interest( prin, cc, time=2, rate=0.09): return prin * time * rate Function call statement Legal//Illegal Reason interest(prin=3000, cc=5) Legal Non-default values provided as named arguments. interest(rate=0.12, prin=5000, cc=4) legal Keyword arguments can be used in any order and for the argument skipped, there is a default value interest(rate=0.05, 5000, 3) Illegal Keyword argument before positional arguments. interest(5000, prin=300, cc=2) illegal Multiple values provided for prin interest(5000, principal=300, cc=2) Illegal Undefined named used(principal is not a parameter) Interest(500, time=2, rate=0.05) Illegal A required argument (cc) is missing.
  • 32.
    Given the following functionfun1() Please select all the correct function calls def fun1(name, age): print(name, age) 1) fun1("Emma", age=23) 2) fun1(age =23, name="Emma") 3) fun1(name=”Emma”, 23) 4) fun1(age =23, “Emma”)
  • 33.
    Quick recap ■ Whichof 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)
  • 34.
    Practical Question 8 ANumber 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 Save the above as a module perfect.py and use in the program main.py as a menu driven program.
  • 35.
    XII Computer Science Session5 User Defined Functions 26th March 2021
  • 36.
    Learning Outcomes ■ Revisedifferent type of parameters through an interaction q/a session ■ Understand how to pass different type of sequences to functions
  • 37.
    QUIZ OF THEDAY 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
  • 38.
    Quiz of theday 1) What will be the output of the following Python code? def func(a, b=5, c=10): print('a is', a, 'and b is', b, 'and c is', c) func(3, 7) func(25, c = 24) func(c = 50, a = 100)
  • 39.
    Quiz of theday (Answer) 1) What will be the output of the following Python code? def func(a, b=5, c=10): print('a is', a, 'and b is', b, 'and c is', c) func(3, 7) func(25, c = 24) func(c = 50, a = 100) ANSWER a is 3 and b is 7 and c is 10 a is 25 and b is 5 and c is 24 a is 100 and b is 5 and c is 50
  • 40.
    Quiz of theday 2) Name the invalid function calls def student(firstname, lastname ='Mark', standard ='Fifth'): print(firstname, lastname, 'studies in', standard, 'Standard') a)student() b) student(firstname ='John', 'Seventh’) c) student(subject ='Maths') d) student(firstname ='John’) e) student(firstname ='John', standard ='Seventh')
  • 41.
    Quiz of theday (Answer) 2) Name the invalid function calls def student(firstname, lastname ='Mark', standard ='Fifth'): print(firstname, lastname, 'studies in', standard, 'Standard') a)student() #invalid because required argument is missing b) student(firstname ='John’, standard='Seventh’) #invalid non keyword argument after keyword argument c) student(subject ='Maths') #unknown keyword argument d) student(firstname ='John’) #valid e) student(firstname ='John', standard ='Seventh') #valid
  • 42.
    Passing sequence tofunctions Any sequence can be passed as an argument to the function Example the below program counts number of 2 digit numbers in a program def function(l): c=1 for i in l: if(len(str(i))==2): c+=1 return c l=[2,12,232,15,6,19,24] print(function(l))
  • 43.
    Passing sequence tofunctions – Mutable sequence – The function is supposed to calculate and return an answer – The function is supposed to make changes in the sequence
  • 44.
    Example of sequencereturning single answer UDF to find the number of perfect numbers from a list 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))
  • 45.
    Changing the sequencein a function UDF to swap adjacent numbers in a list def swap(x): x=l #aliasing for i in range(0,len(l)-1,2): l[i],l[i+1]=l[i+1],l[i] #Statement to swap list l=[1,2,3,4,5,6] swap(l) print(l) NOTE: If you can making changes to a mutable datatype in a function. You do not need to return
  • 46.
    Question Write a UDFto take a list and remove all even numbers from it def remove(l): pass L= [6,5,3,1,9,14] remove(L) print(L)
  • 47.
    Scope of avariable Scope of a variable means the section of the code where the variable is visible A variable can have the following scopes in Python Local Scope Global Scope
  • 48.
    XII Computer Science Session6 User Defined Functions 31st March 2021
  • 49.
    Learning Outcomes We willunderstand Will solve CBSE Programming questions of Sequences in UDF Will get acquainted with the Concept of scope and life Will be able to Categorize of variables in different scopes
  • 50.
  • 51.
    CBSE Questions ■ Write amethod in python to display the elements of list thrice if it is a number and display the element terminated with '#' if it is not a number. ■ For example, if the content of list is as follows: ■ List=['41','DROND','GIRIRAJ','13','ZARA’] ■ 414141 ■ DROND# ■ GIRlRAJ# ■ 131313 ■ ZARA#
  • 52.
    Solution def display(l): for iin l: if i.isdigit(): print(i*3) else: print(i+'#')
  • 53.
    CBSE Question ■ Writedefinition 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 ■ MZ
  • 54.
    Solution def msearch(states): for iin states: if i.startswith('M’): print(i)
  • 55.
    Scope of a variable Scopeof a variable means the section of the code where the variable is visible A variable can have the following scopes in Python Local Scope Global Scope
  • 56.
    Local Scope A variablecreated inside a function belongs to the local scope of that function, and can only be used inside that function. def myfunc(): x = 300 print(x) myfunc()
  • 57.
    def function(): a=100 print(a) a+=100 function() print(a) function() Important characteristics of local variables Theirscope is only inside the function they are created They retain their life only till the function is getting executed
  • 58.
    def function(): a=100 print(a) a+=100 def f2(): a=20 print(a) function() f2() deffunction(): a=100 print(a) a+=100 def f2(): a=20 print(a) function() f2() a=50 print(a) Example 2 of local variables
  • 59.
    a=5 def function(): print(a) function() a=a+8 function() Global Variables ■ Avariable 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 executes
  • 60.
    XII Computer Science Session 7 UserDefined Functions 5th April 2021
  • 61.
    Learning Outcomes ■ Wewill be able to understand ■ Local and Global scope ■ global and nonlocal keyword ■ Namespace resolution ■ LEGB Rule
  • 62.
    Formal Arguments are local to the function •def swap(a,b): • a,b=b,a • print(a,b) • a=10 • b=20 • swap(a,b) • print(a,b) Call by Value
  • 63.
    Only changes made to mutable datatypes reflects back • defincrease(l1): #l1=l • for i in range(len(l1)): • l1[i]+=i • l=[2,4,5,7,10,12] • increase(l) • print(l) Call by Reference
  • 64.
    Only changes made to mutable datatypes reflects back def createDictionary(d): #Letsbegin the code of finding frequency for i in l: if i not in d: d[i]=1 else: d[i]+=1 d={} l=[6,3,3,1,2,3,6,9,1,1,3] createDictionary(d) print(d)
  • 65.
  • 66.
    def f(): global s print(s) s= "Python has extensive library support" print(s) s = "Python is a dynamic language" f() print(s) How to edit global variables in the function ■ We can tell Python that we need to edit the global variable by using the global keyword
  • 67.
    Recap Question 1 •Differentiate between call by value and call by reference?
  • 68.
    Recap Question 2 def function(bar): bar.append(42) bar.append([42]) answer_list= [] function(answer_list) print(answer_list) print(len(answer_list))
  • 69.
    Recap Question 3 a=10 b=20 def change(): globala,b a=45 b=56 change() print(a) print(b)
  • 70.
  • 71.
    Recap Question 5 def f(p,q, r): global s p = 10 q = 20 r = 30 s = 40 print(p,q,r,s) p,q,r,s = 1,2,3,4 f(5,10,15) print(p,q,r,s)
  • 72.
    XII Computer Science Session 8 UserDefined Functions 8th April 2021
  • 73.
    Recap Question 1 x= 50 def fun1(): # your code to assign x=20 fun1() print(x) # it should print 20
  • 74.
    Recap Question 2 def foo(x,y): global a a = 42 x,y = y,x b = 33 b = 17 c = 100 print(a,b,x,y) a, b, x, y = 1, 15, 3,4 foo(17, 4) print(a, b, x, y)
  • 75.
    Recap Question 3 a=9,10 defg(): global a a=a+(4,5) def h(): a=(4,5) h() print(a) g() print(a)
  • 76.
    Nested Functions a=10 def outer(): a=15 definner(): print(a) #local variable of outer LEGB 15 inner() outer() print(a) #10 ■ A function can contain function inside it. ■ It is the local function. ■ It is only callable from the function inside which it is created
  • 77.
    Nested functions to access global variables a=10 def outer(): a=15 definner(): global a print(a) inner() outer() print(a)
  • 78.
    Nested functions to access variables of outer function a=10 defouter(): a=15 def inner(): nonlocal a print(a) inner() outer() print(a)
  • 79.
    Question 1 Output of thecode def outer(): a=10 def inner(): a+=15 print(a) inner() print(a) outer()
  • 80.
    Question 2 Output of thecode val = 0 def f1(): val = 5 def f2(): val = 7.5; def f3(): nonlocal val; val = 10; print("f3:", val); f3(); print("f2:", val); f2(); print("f1:", val); f1();
  • 81.
    Nested and Global functions canmanipulate mutable datatypes without using global/local keyword x=[] def function(): x.append(4) print(x) function() print(x)
  • 82.
    Nested and Global functions canmanipulate mutable datatypes without using global/local keyword def outer(): a=[10] def inner(): a.append(15) print(a) inner() print(a) outer()
  • 83.
    Nested and Global functions canmanipulate mutable datatypes without using global/local keyword def outside(): d = {'outside': 1} def inside(): d['inside'] = 2 print(d) #d={‘outside’:1,’inside’:2} inside() print(d) #d={‘outside’:1,’inside’:2} outside()
  • 84.
    XII Computer Science Session 9 UserDefined Functions 9th April 2021
  • 85.
    Let’s Revise l=[14,5,2] a=l[0] def outer(): l.append('a') a=5 definner(): 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) 3 [14, 5, 2, 'a', 3] 5 [14, 5, 2, 'a', 3] 14
  • 86.
    Let’s revise a='new' def outer(a): a=a+'year' definner1(): global a a=a+'days' def inner2(): nonlocal a a=a+'happy' inner1() print(a) inner2() print(a) outer(a) print(a) newyear newyearhappy newdays
  • 87.
    Let’s revise x=15 def function(): x=2 globalinner print(x) def inner(): global x x=5 def f1(): x=10 def inner(): nonlocal x x=x+3 print(x) print(x) inner() f1() function() inner() print(x) 10 13 2 5
  • 88.
    Namespace • Every valueis associated to a variable • Namespace is a dictionary of Names
  • 89.
    Namespace • Example • a=10 •b=20 • c=30 • Namespace will be {a:10,b:20,c=30}
  • 90.
    Namespace Different type ofNamespaces ■ Local ■ Enclosed ■ Global ■ Built in a_var = 5 b_var = 7 def outer_foo(): global a_var a_var = 3 b_var = 9 def inner_foo(): global a_var a_var = 4 b_var = 8 print('a_var inside inner_foo :', a_var) print('b_var inside inner_foo :', b_var) inner_foo() print('a_var inside outer_foo :', a_var) print('b_var inside outer_foo :', b_var) outer_foo() print('a_var outside all functions :', a_var) print('b_var outside all functions :', b_var)
  • 91.
    Check local andglobal variables of a function a=10 def phone(): b=50 print("b",globals()) print("b",locals()) def inner(): c=20 nonlocal b print("c global",globals()) print("c local",locals()) inner() phone() global variables ‘a’:10 ‘phone’:{‘function phone’} Local variables ‘b’:50 c global variables ‘a’:10 C local variables ‘c’:20 ‘b’:50
  • 92.
    LEGB Rule • arelisted 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. • Local(L): Defined inside function/class • Enclosed(E): =Nonlocal Defined inside enclosing • functions(Nested function concept) • Global(G): Defined at the uppermost level • Built-in(B): Reserved names in Python builtin modules