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()
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)
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
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.
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
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
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#
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
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()
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?
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
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()
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