[go: up one dir, main page]

0% found this document useful (0 votes)
6 views92 pages

list

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 92

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
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
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

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)
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
2000#100
print(P,'#’,Q) 100$200
return Q 2000#200
A=100 100$200
1000#100
B=200 100$200
A=Alter(A,B)
print(A,"$",B)
B=Alter(B)
print(A,"$",B)
A=Alter(A) 100
print(A,"$",B)
XII Computer
Science

Session 4

User Defined
Functions
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 Arguments are given
default value in Function value in Function call
definition
Allows function call to Allows function call to
have variable no of change the position of
arguments arguments
Example Example
def function(a,b=10): def function(a,b):
pass pass
function(20) 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
defarguments
interest( prin, cc, time=2,
rate=0.09):
return prin * time * rate
Function call statement Legal// Reason
Illegal
interest(prin=3000, cc=5) Legal Non-default values provided as named
arguments.
interest(rate=0.12, legal Keyword arguments can be used in any order
prin=5000, cc=4) 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, illegal Multiple values provided for prin


cc=2)
interest(5000, principal=300, Illegal Undefined named used(principal is not a
cc=2) parameter)
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


XII Computer Science

Session 5
User Defined
Functions
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) ANSWER
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is
func(3, 7) 24
func(25, c = 24) a is 100 and b is 5 and c is
func(c = 50, a = 100) 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
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


■ Write a method in python to display
the elements of list thrice if it is a
number and display the element

CBSE terminated with '#' if it is not a


number.

Questio ■ For example, if the content of list is


as follows:
ns ■ List=['41','DROND','GIRIRAJ','13','ZAR
A’]

■ 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

Scope of A variable can have the


following scopes in Python
a
variable Local Scope

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

■ We will be able to understand


■ Local and Global scope
■ global and nonlocal keyword
■ Namespace resolution
■ LEGB Rule
Formal •def swap(a,b): Call by Value
Argumen • a,b=b,a
ts are •
•a=10
print(a,b)

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

Global def function():


print(a)
variabl a=a+2
function()
es in
UDF
■ We can tell Python that we need to edit the
How to global variable by using the global keyword

edit
global def f():
variables global s
print(s)
in the s = "Python has extensive library
function support"
print(s)

s = "Python is a dynamic language"


f()
print(s)
Recap Question 1
•Differentiate between call by value
and call by reference?
def function(bar):
bar.append(42)
Recap bar.append([42])

Question answer_list = []
2 function(answer_list)
print(answer_list)
print(len(answer_list))
a=10
b=20
def change():

Recap global a,b


a=45
Question b=56
change()
3 print(a)
print(b)
def change(l=[]):
l.insert(1,33)
l.extend("new”)
Recap print("l”,l)

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():

Question val = 7.5;


def f3():

2 Output nonlocal val;


val = 10;
of the print("f3:", val);
f3();
code print("f2:", val);
f2();
print("f1:", val);
f1();
Nested and
Global x=[]
functions can def function():
manipulate x.append(4)
mutable
datatypes print(x)
without function()
using print(x)
global/local
keyword
Nested and
Global def outer():
functions a=[10]
can def inner():
manipulate a.append(15)
mutable print(a)
datatypes
inner()
without
using print(a)
global/local outer()
keyword
Nested and
def outside():
Global
d = {'outside': 1}
functions
def inside():
can
d['inside'] = 2
manipulate
print(d)
mutable #d={‘outside’:1,’inside’:2}
datatypes inside()
without print(d)
using #d={‘outside’:1,’inside’:2}
global/local outside()
keyword
XII Computer
Science

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

Namespace def outer_foo():


global a_var
a_var = 3
b_var = 9
def inner_foo():
global a_var
Different type of Namespaces a_var = 4
b_var = 8
print('a_var inside inner_foo
:', a_var)
■ Local print('b_var inside inner_foo
■ Enclosed :', b_var)
inner_foo()
■ Global print('a_var inside outer_foo :', a_var)
print('b_var inside outer_foo :', b_var)
■ Built in 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():
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.

•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

You might also like