0% found this document useful (0 votes)
5 views

Function

Uploaded by

Vinod Srivastava
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Function

Uploaded by

Vinod Srivastava
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Python Notes Class XI User Defined Function

Python has rich collections of built-in functions. Still we need user defined function for the following
reasons:
1. Functions help divide a program into modules. This makes the code easier to manage and debug
2. It implements code reuse. To reuse the call, a function needs to be called (invoked)

Python function has two parts:


a) Function Header: it starts with keyword def, contains the name of the function and optional list of
formal parameters, that is, it is not necessary that every function must have parameters.
b) Function Block: it is the block after the function header. Function block contains equally indented
statements that carry out certain action inside the function. Function block may contain the optional
return statement. An example of a user defined function is given below:
User Defined def myfactorial(n): Function Header
Function fact=1
for k in range(1,n+1): Function Block
OR
fact*=k Or
Function
return fact Function Body
Definition

Name of the function is myfactorial(), function returns a value and it has a formal parameter n.
Function name is myfactorial(). In Python, formal parameter does not have any parameter (this issue
will be discussed later). Function’s return statement serves two purposes:
a) It terminates the function
b) Returns a value to the caller

When a function returns a value, the function may be called (invoked) as:
1. VarName=FunctionName(ActualParaList)
2. print(FunctionName(ActualParaList))

Complete Python script including user defined function myfactorial() with parameter no.
def myfactorial(no): • myfactorial() – user defined function
fact=1 • no – Formal parameter
for k in range(1, no+1):
• Function call is:
fact*=k; f1=myfactorial(n)
return fact f2=myfactorial(n+3)
f3=myfactorial(8)
n=int(input('Input n? ')) print(myfactorial(5))
f1=myfactorial(n) myfactorial(6)
f2=myfactorial(n+3)
• Actual parameter:
f3=myfactorial(8)
1st call – n (variable)
print(f1)
print(f2) 2nd call – n+3 (expression)
print(f3) 3rd call – 8 (constant)
print(myfactorial(5)) 4th call – 5 (constant)
myfactorial(6) 5th call – 6 (constant)

Running of the Python script produces following outputs:


Input n? 7
Variables f1, f2 and f3 stores the return values of myfactorial()
5040
0320 for the first call, for the second call and for third call respectively. Values
3628800 stored in f1, f2 and f3 are then displayed with print(). Fourth call
120 of the function is directly from print() and it displays the return value
No output of myfactoral(). Last call to myfactorial(6) does not display
any output since the return value of the function is discarded.

FAIPS, DPS Kuwait Page 1 / 10 ©Bikram Ally


Python Notes Class XI User Defined Function
A function with return statement will always return a value to the caller. A function can return more
than one values to the caller. But for the time being we will discuss functions that returns only one value.
Generally, a return statement is followed by either a variable or an expression or a constant. Value of
the variable / expression / constant is returned to the caller by a return statement. Just a return
statement without any variable/expression/constant will return None to the caller. A function without a
return statement also returns a value None. Complete Python script including user defined function
myfactorial() with parameter n and without return statement is given below.
def myfactorial(no): Now edited myfactorial() does not return any value.
fact=1 Factorial calculated is displayed within the function.
for k in range(1, no+1): When a function does not return any value, function call
fact*=k; is FuncName(Parameter). Let us assume inputted
print(fact) value of n is 5. First call to the function display factorial
n=int(input('Input n? ')) of n, second call to the function display factorial of n+2
myfactorial(n)
and third call to the function displays factorial 8 and
myfactorial(n+2)
finally None is displayed.
print(myfactorial(8))

Running of the Python script produces following outputs:


Input n? 5
120
5040
40320
None

Parameter is used to transfer data between caller and user defined function. The data transfer can be either
one-way or it can be two ways. Parameter used in the function header is called formal parameter.
Parameter used during the function call is called actual parameter. Formal parameter receives value from
actual parameter. Data type of formal parameter depends on data type of actual parameter. As shown in
the above example, actual parameter can either be a variable or an expression or a constant. But formal
parameter is a variable. When invoking a function list of actual parameters must be equal to list of formal
parameters. List of actual parameters must be compatible with list of formal parameters.
def add(a, b): First call to function has two int as actual parameters, values stored
t=a+b two format parameters are added and their sum is displayed. Second
print(t) call to function has an int and a float (int and float can be added) as
actual parameters and their sum is displayed. Third call to function has
add(20,20) #call #1 two float actual parameters and their sum is displayed. Fourth call to
add(10,15.5) #call #2 function has two str (two strings are concatenated) as actual parameters
add(5.7,8.8) #call #3 and concatenated string is displayed. Fifth call to function has an int
add('DP','S') #call #4 and a str as actual parameters and they are not compatible hence run-
add(20,'DPS') #call #5 time error. Sixth call to function has a str and a float as actual
add('DPS',5.3)#call #6 parameter and they are not compatible hence run-time error. Seventh
add(40) #call #7 call and eight call to function, number of actual parameter(s) does not
add(23,45,64) #call #8 match with number formal parameters and hence run-time error.

Running of the Python script produces following outputs:


40
25.5
14.5
FAIPS
Triggers Run-time Error
Triggers Run-time Error
Triggers Run-time Error
Triggers Run-time Error
FAIPS, DPS Kuwait Page 2 / 10 ©Bikram Ally
Python Notes Class XI User Defined Function
Global variable vs Local variable
All variables in a program may not be accessible at all locations in that program. This depends on where
a variable has been declared. The scope of a variable determines the portion of the program where a Python
script can access a particular variable. There are two basic scopes of variables in Python:
• Global variable
• Local variable

Variable that are declared inside a function body (block) have a local scope, and a variable declared outside
(either after or before) have a global scope. This means that local variable can be accessed only inside the
function in which they are declared, whereas global variable can be accessed throughout the Python script
(anywhere in the program). When a function is called, the variable declared inside its body is brought into
scope.
Variables x and y are global variables since
x=60 #x Global variable variable x is declared before function add()
def add(m, n): and variable y is declared after function add().
z=m+n #z Local variable Variables x and y can be used anywhere in the
print(x,y,z) #Displays 60 DPS 30 Python script – anywhere in the program.
y='DPS' #y Global variable Variable z is a local variable created inside the
add(10, 20) function add() – variable z can be used inside
print(x,y) #Displays 60 DPS the function add() only.

What happens when a local variable is accessed outside its scope? To answer the question a small Python
script will is given below:

x=100 #x Global variable Variables x and y are global variables.


def foo():
Variable z is a local variable created
y='Kuwait' #y Local variable
print(x,y,z) #Displays x, y and z inside the function foo().
The last print(x,y,z) is flagged
z=7.2 #z Global variable as syntax error since local variable y is
foo() accessed outside its scope.
print(x,y,z) #Run-time error

Keyword global
As discussed earlier, a global variable can be accessed through out the program. But this may not be true
always. Let us write a small Python script to see what happens.

x=10 The output seems little strange. Function foo() did not update global
def foo(): variables x and y. A global variable can be accessed anywhere in the script
x=100 (program) but global variable cannot be updated in inside a function. In our
y=200 example, function foo() did not update global variables x and y. This is
print(x,y)
because, statement x,y=100,200 creates two local variables x and y. The
y=20
statement print(x,y) displays the local variables x and y. But Inside the
print(x,y)
foo() caller, print(x,y) displays global variables x and y. So the question is
print(x,y) how to update global variables x and y inside the function foo()?

Running of the Python script produces following outputs:


10 20
100 200
10 20

By using the keyword global, we can update one can update a global variable. Edited Python script is
given below with the keyword global.
FAIPS, DPS Kuwait Page 3 / 10 ©Bikram Ally
Python Notes Class XI User Defined Function
x=10 x=10
def foo(): def foo():
global x, y x, y=100, 200 #Syntax error
x, y=100, 200 global x, y
print(x,y) print(x,y)
y=20 y=20
foo() foo()
print(x,y) print(x,y)
Running of the Python script produces following Running of the Python script produces syntax error
outputs: because keyword global is used after the statement
100 200 x, y=100, 200
100 200 Keyword global to be used before the updation.
The keyword global, will make variables x and y as global variable and hence the variables x and y can
be updates inside the function foo(). The keyword global is to be used before accessing or updating the
global variables x and y. Without using the keyword global, variable created inside a function with same
name as a global variable, becomes the local variable.
x=10 x=10
def foo(): def foo():
global x global y
x, y=100, 200 x, y=100, 200
print(x,y) print(x,y)
y=20 y=20
foo() foo()
print(x,y) print(x,y)
Running of the Python script produces following Running of the Python script produces following
outputs: outputs:
100 200 100 200
100 20 10 200
Variable x is global variable and variable y is a local Variable y is global variable and variable x is a local
variable. Global variable x is updated. variable. Global variable y is updated.

Keyword global has to be used in every function where a global variable is to be updated.
x=10 x=10
def foo(): def foo():
global x global x
x=100 x=100
print(x) print(x)
def moo(): def moo():
x=1000 #x is local to moo() global x
print(x) x=1000
foo() print(x)
print(x) foo()
moo() print(x)
print(x) moo()
print(x)
Running of the Python script produces following Running of the Python script produces following
outputs: outputs:
100 100
100 100
1000 1000
100 1000
Without the keyword global, x is a local to moo() Because of the keyword global in the function
and hence global variable x does not get updated. moo(), global variable x get updated.
FAIPS, DPS Kuwait Page 4 / 10 ©Bikram Ally
Python Notes Class XI User Defined Function
Keyword global can be used to create a global variable inside a user defined function.
x=10 Global variable x=10 is created right in the beginning. Inside
def foo(): the function foo(), global variable y is created. Inside the
global x, y function foo(), global variable x is 100 and global variable y
x, y=100,200 is 100. Function print(x,y) after foo() displays 100
print(x,y)
100. Inside the function moo(), global variable x is 1000 and
def moo():
global variable y is 1000. Function print(x,y) after foo()
global x, y
x, y=1000,2000 displays 1000 1000.
print(x,y) Running of the Python script produces following outputs:
print(x) 10
foo() 100 200
print(x,y) 100 200
moo() 1000 2000
print(x,y) 1000 2000

Use of keyword global:


1. A global variable is updated inside a function
2. A global variable can be created inside a function and can be used in the function and after the function

Difference between global variable and local variable


Global Variable Local Variable
• Created outside the function, either before or • Crated only inside the function
after a function
• Can be used throughout the program / script • Can be used inside the function

Difference between actual parameter and formal parameter


Actual Parameter Formal Parameter
• Used during the function call / invocation • Created in the function header
• Can be either be variable / expression / constant • Can only be a variable

By using global variable inside a function, one can eliminate use of formal parameter in a function.
def chkarmstrong(): def chkpalindrome():
global n global n
s, t, power=0, n, len(str(n)) s, t=0, n
while t: while t:
d=t%10 d=t%10
s+=d**power s=10*s+d
t//=10 t//=10
if s==n: if s==n:
print('Armstrong') print('Palindrome')
else: else:
print('Not Armstrong') print('Not Palindrome')
n=int(input('Input n? ')) n=int(input('Input n? '))
chkarmstrong() chkpalindrome()

Non-recursive code for some important functions are given below:


1!+2!+3!+4!+…+n! 2!+4!+6!+8!+…+(2*n)!
def sumofseq(n): def sumofseq(n):
s=1 s=f=1
f=1 for k in range(1, n+1):
for k in range(1, n+1): t=2*k
f*=k f*=(t-1)*t
FAIPS, DPS Kuwait Page 5 / 10 ©Bikram Ally
Python Notes Class XI User Defined Function
s+=f s+=f
return s #Or, print(s) return s #Or, print(s)
1!+3!+5!+7!+…+(2*n-1)! 1!+3!+5!+7!+…+(2*n-1)!
def sumofseq(n): def sumofseq(n):
f=1 s=1
s=1+x for k in range(1, n):
for k in range(1, n): f=1
t=2*k+1 for j in range(1, 2*k):
f*=(t-1)*t f*=j
s+=f s+=f
return s #Or, print(s) return s #Or, print(s)
1+x+x2+x3+x4+…+xn 1+x2+x4+x6+x8+…+x2n
def sumofseq(x, n): def sumofseq(x, n):
s=p=1 s=p=1
for k in range(1, n+1): for k in range(1, n+1):
p*=x p*=x*x
s+=p s+=p
return s #Or, print(s) return s #Or, print(s)
1+x+x3+x5+x7+…+x2n-1 1+1/x+1/x2+1/x3+1/x4+…+1/xn
def sumofseq(x, n): def sumofseq(x, n):
s, p=1, 1/x s=p=1
for k in range(1, n+1): for k in range(1, n+1):
p*=x*x p*=1/x #Or, p/=x
s+=p s+=p
return s #Or, print(s) return s #Or, print(s)
1+x/1!+x2/2!+x3/3!+x4/4!+…+xn/n! 1+x2/2!+x4/4!+x6/6!+x8/8!+…+x2n/(2n)!
def sumofseq(x, n): def sumofseq(x, n):
p=f=s=1 p=f=s=1
for k in range(1, n+1): for k in range(1, n+1):
p*=x p*=x*x
f*=k f*=(2*k-1)*2*k
s+=p/f s+=p/f
return s #Or, print(s) return s #Or, print(s)
1+x/1!+x3/3!+x5/5!+x7/7!+…+x2n-1/(2n-1)! 1+x/1!+x3/3!+x5/5!+x7/7!+…+x2n-1/(2n-1)!
def sumofseq(x, n): def sumofseq(x, n):
s=1+x s=1
p=x for k in range(1, n+1):
f=1 p=f=1
for k in range(1, n+1): for j in range(1, 2*k):
p*=x*x p*=x
f*=(2*k+1)*2*k f*=j
s+=p/f s+=p/f
return s #Or, print(s) return s #Or, print(s)
#count digits #sum of digits
def countdigit(n): def sumdigit(n):
d=0 s=0
while n: while n:
d+=1 d=n%10
n//=10 s+=d
return d #Or, print(d) n//=10
return s #Or, print(s)
#sum of square of digits #sum of cube of digits
def sumdigitsqr(n): def sumdigitcube(n):
s=0 s=0
FAIPS, DPS Kuwait Page 6 / 10 ©Bikram Ally
Python Notes Class XI User Defined Function
while n: while n:
d=n%10 d=n%10
s+=d*d #Or, s+=d**2 s+=d*d*d #Or, s+=d**3
n//=10 n//=10
return s #Or, print(s) return s #Or, print(s)
#products of digits #products of digits ignore 0
def productdigit(n): def productdigit(n):
p=1 p=1
while n: while n:
d=n%10 d=n%10
p*=d if d: p*=d
n//=10 n//=10
return p #Or, print(p) return p #Or, print(p)
#sum of reciprocal of digits #reversing digits
def sumdigitreci(n): def reversedigits(n):
s=0 s=0
while n: while n:
d=n%10 d=n%10
if d: s+=1/d s=10*s+d
n//=10 n//=10
return s #Or, print(s) return s #Or, print(s)
#check for Armstrong Number #check for Palindrome Number
def chkarmstrong(n): def chkpalindrome(n):
s, t, power=0, n, len(str(n)) s, t=0, n
while t: while t:
d=t%10 d=t%10
s+=d**power s=10*s+d
t//=10 t//=10
if s==n: if s==n:
print('Armstrong') print('Palindrome')
else: else:
print('Not Armstrong') print('Not Palindrome')
#Or, return int(s==n) #Or, return int(s==n)
#HCF of two numbers #LCM of two numbers
def hcf(a,b): def lcm(a,b):
r=1 p, r=a*b, 1
while r: while r:
r=a%b r=a%b
a=b a=b
b=r b=r
return a #Or, print(a) return p//a #Or, print(p//a)
#check for Prime Number #check for Prime Number
def chkprime(n): def chkprime(n):
k=2 k, prime=2, 1
prime=1 while k<n//2:
while k<n//2 and prime==1: if n%k==0:
if n%k==0: prime=0
prime=0 break
k+=1 k+=1
if prime==1: if prime==1:
print('Prime') print('Prime')
else: else:
print('Composite') print('Composite')
#Or, return prime #Or, return prime
FAIPS, DPS Kuwait Page 7 / 10 ©Bikram Ally
Python Notes Class XI User Defined Function
#check for Prime Number #check for Prime Number
def chkprime(n): def chkprime(n):
prime=1 for k in range(2, n//2):
for k in range(2, n//2): if n%k==0:
if n%k==0: print('Composite Number')
prime=0 #Or, prime=0
break break
if prime==1: else:
print('Prime') print('Prime Number')
else: #Or, prime=1
print('Composite') #Or, return prime
#Or, return prime
#check for Fibonacci Number #check for Fibonacci Number
def chkfibo(n): def chkfibo(n):
f1, f2=0, 1 f1=0
while n>=f1: f2=1
if n==f1: fibo=1
print('Fibonacci No') while n>=f1:
fibo=1 if n==f1:
break fibo=1
elif n>f1: f1,f2=f2,f1+f2
print('Not Fibonacci No') if fibo:
fibo=0 print('Fibonacci No')
break else:
f1,f2=f2,f1+f2 print('Not Fibonacci No')
#return fibo #return fibbo
#Generate first n Fibonacci numbers #Generate first n Fibonacci numbers
def genfibbo(n) def genfibbo(n)
f1=0 f1, f2, k=0, 1, 1
f2=1 while k<=n:
for k in range(n): print(f1)
print(f1) f1, f2=f2, f1+f2
f1, f2=f2, f1+f2 k+=1
#check for Perfect Number #check for Perfect Number
def chkperfect(n) def chkperfect(n)
s=0 k, s=0, 1
for k in range(1, n): while k<=n:
if n%k==0: if n%k==0: s+=k
s+=k k+-1
if s==n: if s==n:
print('Perfect Number') print('Perfect Number')
else: else:
print('Not Perfect Number') print('Not Perfect Number')
#Or, return int(s==n) #Or, return int(s==n)
#Generate Prime Numbers #Generate Prime Numbers
def genprime(n): def genprime(n):
for num in range(2, n+1): for num in range(2, n+1):
for k in range(2, num//2): prime=1
if num%k==0: for k in range(2, num//2):
break if num%k==0:
else: prime=0
print(num) break
if prime: print(num)

FAIPS, DPS Kuwait Page 8 / 10 ©Bikram Ally


Python Notes Class XI User Defined Function
#Generate Armstrong Numbers #Generate Palindrome Numbers
def genarmstrong(n): def genpalidrome(n):
for no in range(10, n+1): for no in range(10, n+1):
s,t,power=0,no,len(str(no)) s,t=0,no
while t: while t:
d=t%10 d=t%10
s+=d**power s=10*s+d
t//=10 t//=10
if s==no: if s==no:
print(no) print(no)

Required argument (parameter), Keyword argument (parameter)


Arguments (parameters) are used to transfer data between the caller and the function. Generally, a
function with list of formal argument (parameters) must have matching list of actual arguments (or
parameters). List of actual arguments matching list of formal arguments is called Required Arguments.
An example is given below:

def display(roll, name, marks): List of formal arguments


print('Roll=',roll)
print('Name=',name)
print('Marks=',marks)
ro,na,ma=12,'RANJAN YADAV', 78.5
display(ro, na, ma)
display(na, ma, ro) List of actual arguments ro, na and
display(ma, ro, na) ma are also called required arguments

Outputs produced by the script:


Roll= 12
Name= RANJAN YADAV
Marks= 78.5
Roll= RANJAN YADAV
Name= 78.5
Marks= 12
Roll= 78.5
Name= 12
Marks= RANJAN YADAV

In Python there is no strict data type for any variable. Value stored in an actual argument decides data
type of the formal argument. Hence last two calls to function display() are syntactically correct but
logically wrong. To eliminate this kind of logical error we need Keyword argument. Using Keyword
Argument, formal argument's names are included with the actual arguments. Keyword arguments is
nothing but the list of actual arguments (formal argument names are assigned values during the function
call). Using keyword arguments, the list of actual arguments can be in any order but correct values will
be assigned to the list of formal arguments. An example is given below:

def display(roll, name, marks): List of formal arguments


print('Roll=',roll)
print('Name=',name)
print('Marks=',marks)
ro,na,ma=12,'RANJAN YADAV', 78.5
display(roll=ro, name=na, marks=ma) Keyword Arguments: Formal
display(name=na, marks=ma, roll=ro) argument's names are assigned
display(marks=ma, roll=ro, name=na) values during the function call

FAIPS, DPS Kuwait Page 9 / 10 ©Bikram Ally


Python Notes Class XI User Defined Function
Outputs produced by the script:
Roll= 12
Name= RANJAN YADAV
Marks= 78.5
Roll= RANJAN YADAV
Name= 78.5
Marks= 12
Roll= 78.5
Name= 12
Marks= RANJAN YADAV

Above example shows that using keyword arguments, even if the order of actual arguments does not
match with order of formal arguments but correct values are assigned to the formal arguments.

Default argument (parameter)


As discussed above, every function with arguments must have same number of formal arguments and
actual arguments. But we will see now that may not true every time. In Python, formal arguments can be
assigned constant values and that function can be called without any actual arguments. Constant values
assigned to the formal arguments are called Default Arguments. When actual argument is present during
the function call, formal argument's default value is replaced by value present in the actual argument.
Default arguments always starts from the right. An example is given below:

def foo(ch='*', n=10): Explanation of outputs


for x in range(n): foo() calls the function without any actual arguments.
print(ch, end='') Function foo() uses default values of the formal arguments
print() to display **********. foo('#') calls the function
foo() with one actual argument. '#' replaces the default of ch but
foo('#') n's default value is still 10. So ########## is displayed.
foo(7) foo(7) calls the function with one actual argument. 7
foo('$',12) replaces the default value of ch but n's default value is still
foo(n=15, ch='@') 10. So, 7777777777 is displayed. foo('$',15) calls
the function with two actual arguments. '$' replaces default
Outputs produced by the script: value of ch and 12 replaces default value of n. So
**********
$$$$$$$$$$$$ is displayed. foo(n=20, ch='@')
##########
7777777777 calls the function with two keyword arguments. '@'
$$$$$$$$$$$$ replaces default value of ch and 20 replaces default value
@@@@@@@@@@@@@@@ of n. So @@@@@@@@@@@@@@@ is displayed.

As mentioned earlier, default arguments start from right. Examples of incorrect use of default arguments
are given below:
def foo(a=10,b,c=30): Syntax error Non-default argument follows default argument.
avg=(a+b+c)/3 Since formal argument b is non-default argument. Possible solution,
print(avg) make formal argument b as default argument.
def foo(a=10,b=20,c): Syntax error Non-default argument follows default argument.
avg=(a+b+c)/3 Since formal argument c is non-default argument. Possible solution,
print(avg) make parameter c as default argument.
def foo(a=10,b,c): Syntax error Non-default argument follows default argument.
avg=(a+b+c)/3 Since formal arguments b and c are non-default arguments. Possible
print(avg) solution, make formal argument b and c as default argument.
def foo(a,b=20,c): Syntax error Non-default argument follows default argument.
avg=(a+b+c)/3 Since formal argument c is non-default argument. Possible solution,
print(avg) make formal argument c as default argument.
FAIPS, DPS Kuwait Page 10 / 10 ©Bikram Ally

You might also like