����Python Programming �
UNIT – IV
Functions
� Functions
*
� Need for Functions
*
*
� Function Definition
*
� Points to define a function
Function Definition
*
Function Call:
*
*
Function to add two numbers
def add( a,b): # function definition
sum= a+b
return sum
a=int(input("enter a number"))
b=int(input("enter a number"))
Result =add(a,b) #function name assigned to a variable
print(“Result is =", Result)
O/P:
enter a number 3
enter a number 4
Result is 7
*
#Example for a function with no argument
def fun():
for i in range(4):
print("welcome")
fun() #function call
O/P:
welcome
welcome
welcome
welcome
*
#mismatch between function parameters
def fun(i,j):
print(i,j)
fun(6) #function call
O/P:
Traceback (most recent call last):
File "C:/Users/user/AppData/Local/Programs/Python/Python37-32/fun1.py", line 3, in <module>
f(6) #function call
TypeError: f() missing 1 required positional argument: 'j'
*
#mismatch between function parameters
def fun(i):
print(i)
fun(6,5) #function call
O/P:
Traceback (most recent call last):
File "C:/Users/user/AppData/Local/Programs/Python/Python37-32/fun1.py", line 3, in <module>
fun(6,5) #function call
TypeError: fun() takes 1 positional argument but 2 were given
*
Sample Program
def fun(i):
print(i)
k=10
fun(k) #function call
O/P:
10
*
#arguments may be passed in the form of expression
def fun(i):
print(i)
fun(5*3+7) #function call
O/P:
22
Variable scope and lifetime
part of the program in which a variable is accessible is called
its scope
duration for which the variable exists is called its lifetime
*
Global and Local Variables
*
Sample Program
a=20 # Global variable
def display(): # user defined function
print(“Inside user-defined function:”,a)
display() # actual program
print(“Outside user-defined function:”,a)
Output:
Inside user-defined function: 20
Outside user-defined function: 20
*
Sample Program
a=20 # Global variable
def display():
b=30 # user defined function
print(“Inside user-defined function:”,a)
print(“Local variable”,b)
display() # actual program
print(“Outside user-defined function:”,a)
*
Sample Program
a=10 # Global variable
def display():
b=20
print(“Global=”,a)
print(“local=”,b)
display()
c=40 # Local variable
print(“local”,c)
print(“Global”,a)
*
Sample Program
a=10 # Global variable # If local and global variable having same name, First preference to local variables.
c=20
def display():
a=20
print(a)
display()
a=40 # Local variable
print(a)
d=a+c
print(d)
*
*
*
# Difference between local and global variables
num1=10 #global variable
print("global variable num1=", num1)
def fun(num2): #num2 is function parameter
print("inside function-local variable num2=",num2)
num3=30 #num3 is a local variable
print("inside function-local variable num3=",num3)
fun(20) #20 is passed as an argument to function
print("global variable num1=", num1)
print("local variable - outside function num3=", num3)
O/P:
global variable num1= 10
inside function-local variable num2= 20
inside function-local variable num3= 30
global variable num1= 10
Traceback (most recent call last):
File "C:/Users/user/AppData/Local/Programs/Python/Python37-32/fun1.py", line 10, in <module>
print("local variable - outside function num3=", num3)
NameError: name 'num3' is not defined
*
# use of global statement
num1=10 #global variable
print("global variable num1=", num1)
def fun(num2): #num2 is function parameter
print("inside function-local variable num2=",num2)
global num3 #num3 is a global variable
num3=30
print("inside function-global variable num3=",num3)
fun(20) #20 is passed as an argument to function
print("global variable num1=", num1)
print("global variable declared inside function - outside function num3=", num3)
O/P:
global variable num1= 10
inside function-local variable num2= 20
inside function-global variable num3= 30
global variable num1= 10
global variable declared inside function - outside function num3= 30
*
#name clash of local and global variable
num=10 #global variable
print("global variable num=", num)
def fun():
num=30
print("inside function-local variable num=",num)
fun()
print("outside function-global variable num=", num)
O/P:
global variable num= 10
inside function-local variable num= 30
outside function-global variable num= 10
*
#modifying a global variable
var="Good" #global variable
print("global variable var=", var)
def fun():
global var
var="Morning"
print("inside function-global variable var=",var)
fun()
print("outside function-global variable var=", var)
var="Evening"
print("outside function-global variable var=", var)
O/P:
global variable var= Good
inside function-global variable var= Morning
outside function-global variable var= Morning
outside function-global variable var= Evening
*
#access of variables in inner and outer functions
def ofun():
o_var=10
def ifun():
i_var=20
print("outer variable inside inner function o_var=",o_var)
print("inner variable inside inner function i_var=",i_var)
ifun()
print("outer variable outside inner function o_var=",o_var)
print("inner variable outside inner function i_var=",i_var)
ofun()
O/P outer variable inside inner function o_var= 10
inner variable inside inner function i_var= 20
outer variable outside inner function o_var= 10
Traceback (most recent call last):
File "C:/Users/user/AppData/Local/Programs/Python/Python37-32/fun1.py", line 10, in <module>
ofun()
File "C:/Users/user/AppData/Local/Programs/Python/Python37-32/fun1.py", line 9, in ofun
print("inner variable outside inner function i_var=",i_var)
NameError: name 'i_var' is not defined :
*
#name clash variables in case of nested functions
def ofun():
var=10
def ifun():
var=20
print("inside inner function var=",var)
ifun()
print("outside inner function var=",var)
ofun()
O/P:
inside inner function var= 20
outside inner function var= 10
*
#name clash variables in case of nested functions-Global statement also doesn't change
def ofun():
var=10
def ifun():
global var
var=20
print("inside inner function var=",var)
ifun()
print("outside inner function var=",var)
ofun()
O/P:
inside inner function var= 20
outside inner function var= 10
*
#Variable defined in global namespace
def fun():
print(str)
str="welcome to functions in Python"
fun()
O/P:
welcome to functions in Python
*
#local variable with same name as that of global variable
def fun():
print(str) #refers global string str
str="inside function"
print(str) #refers local string str
str="welcome to functions in Python"
fun()
O/P:
Traceback (most recent call last):
File "C:/Users/user/AppData/Local/Programs/Python/Python37-32/fun1.py", line 6, in <module>
fun()
File "C:/Users/user/AppData/Local/Programs/Python/Python37-32/fun1.py", line 2, in fun
print(str) #refers global string str
UnboundLocalError: local variable 'str' referenced before assignment
*
#use of global statement is required in name clash
def fun():
global str
print(str) #refers global string str
str="inside function"
print(str) #refers local string str
str="welcome to functions in Python"
fun()
O/P:
welcome to functions in Python
inside function
*
#function without a return statement, prints the value None
def fun(str):
print(str)
x=fun("Welcome")
print(x)
print(fun("Hello Hai"))
O/P:
Welcome
None
Hello Hai
None
*
#To find cube of a number
def cube(x):
return(x**3)
k=int(input("enter a number"))
x=cube(k)
print("cube of a number",k, "is", x)
O/P:
enter a number3
cube of a number 3 is 27
*
#statement after return statement will not be executed
def cube(x):
return(x**3)
print("value of x is",x)
k=int(input("enter a number"))
x=cube(k)
print("cube of a number",k, "is", x)
O/P:
enter a number3
cube of a number 3 is 27
# Python program to find the largest number among the three
numbers
def maximum(a, b, c):
if (a >= b) and (a >= c):
largest = a
elif (b >= a) and (b >= c):
largest = b
else:
largest = c
return largest
# Driven code
a = 10
b = 14
c = 12
print(maximum(a, b, c))
*
More on Defining Functions
*
������� Required arguments
def fun():
print("Hello")
fun("Hi")
O/P:
Traceback (most recent call last):
File "C:/Users/user/AppData/Local/Programs/Python/Python37-32/fun1.py", line 3, in <module>
fun("Hi")
TypeError: fun() takes 0 positional arguments but 1 was given
*
������� � Required arguments
def fun(str):
print(str)
fun()
O/P:
Traceback (most recent call last):
File "C:/Users/user/AppData/Local/Programs/Python/Python37-32/fun1.py", line 3, in <module>
fun()
TypeError: fun() missing 1 required positional argument: 'str'
*
������� Required arguments
def fun(str):
print(str)
fun("Hello")
(or)
def fun(str):
print(str)
str="Hello"
fun(str)
O/P:
Hello
*
������� Keyword arguments
def fun(str, x):
print("string is",str)
print("x is",x)
fun(x=15,str="Hello")
O/P:
string is Hello
x is 15
*
������� Keyword arguments
def fun(str, x):
print("string is",str)
print("x is",x)
fun(x=15,s1="Hello")
O/P:
Traceback (most recent call last):
File "C:/Users/user/AppData/Local/Programs/Python/Python37-32/fun1.py", line 5, in <module>
fun(x=1.5,s1="Hello")
TypeError: fun() got an unexpected keyword argument 's1'
*
������� Keyword arguments
def fun(str, x, y):
print("string is",str)
print("x is",x)
print("y is",y)
x=10
y=[10,"aaa",12.3]
str="Welcome"
fun(x,y,str)
O/P:
string is 10
x is [10, 'aaa', 12.3]
y is Welcome
*
������� Keyword arguments
def fun(str, x, y):
print("string is",str)
print("x is",x)
print("y is",y)
x=10
y=[10,"aaa",12.3]
str="Welcome"
fun(x=x,y=y,str=str)
O/P:
string is Welcome
x is 10
y is [10, 'aaa', 12.3]
*
������� Keyword arguments
def fun(str, x, y):
print("string is",str)
print("x is",x)
print("y is",y)
a=10
b=[10,"aaa",12.3]
c="Welcome"
fun(x=b,y=a,str=c)
O/P:
string is Welcome
x is [10, 'aaa', 12.3]
y is 10
*
������� Default arguments
def fun(name="aaa", course="BTech"):
print("name is",name)
print("course is",course)
fun(name="xxx",course="BE") #Keyword arguments
fun(name="rrr") #default arguments for course
fun() #default arguments for name and course
O/P:
name is xxx
course is BE
name is rrr
course is BTech
name is aaa
course is BTech
*
������� Default arguments
def fun(name="aaa", course):
print("name is",name)
print("course is",course)
fun(name="xxx",course="BE") #Keyword arguments
fun(course="BE") #default arguments for name
O/P:
File "<ipython-input-13-c9a72b30d90a>", line 2 def fun(name="aaa", course): ^ SyntaxError: non-default argument follows default argument
*
������� variable-length arguments
def functionname([arg1,arg2,….] *var_args_tuple):
function statements
return(expression)
*
variable-length arguments
def functionname([arg1,arg2,….] *var_args_tuple):
function statements
return(expression)
*
� �������������Create function with variable length arguments�
def func(*args):
#
# body of the function
#
*
Passing multiple arguments�
def sum(*args):
print(type(args))
print(args)
sum(10, 20)
sum(10, 20, 30)
sum(10, 20, 30, 40)
Output: <class 'tuple'>
(10, 20)
<class 'tuple'>
(10, 20, 30)
<class 'tuple'>
(10, 20, 30, 40)
*
Multiple arguments sum function�
# func
def sum(*args):
result = 0
for arg in args:
result = result + arg
return result
print(sum(10, 20)) # 30
print(sum(10, 20, 30)) # 60
print(sum(10, 20, 30, 40)) # 100
*
variable-length arguments
#program to demonstrate *args in python
def my_func(*argp):
for i in argp:
#printing each element from the list
print(i)
#passing the parameters in function
my_func("Let","us","study","Data Science","and","Blockchain")
Let
us
study
Data Science
and
Blockchain
*
#program to demonstrate *args in python
def my_func(par1,par2,*argp):
#displaying the first parameter
print("The first parameter is: ",par1)
#displaying the second parameter
print("The second parameter is: ",par2)
for i in argp:
#printing each element from the list
print(i)
#passing the parameters in function
my_func("Let","us","study","Data Science","and","Blockchain")
Output:
The first parameter is: Let
The second parameter is: us
study Data Science and Blockchain
*
������� variable-length arguments
def fun(*subj):
print("\n", "likes to read")
for i in subj:
print(i)
fun("xxx","C", "JAVA","PYTHON")
fun("aaa", "C++","PYTHON")
fun("zzz","PYTHON")
fun("ttt")
O/P
likes to read
xxx
C
JAVA
PYTHON
likes to read
aaa
C++
PYTHON
likes to read
zzz
PYTHON
likes to read
ttt
*
������� variable-length arguments
def fun(name, *subj):
print("\n",name, "likes to read")
for i in subj:
print(i)
fun("xxx","C", "JAVA","PYTHON")
fun("aaa", "C++","PYTHON")
fun("zzz","PYTHON")
fun("ttt")
O/P:
xxx likes to read
C
JAVA
PYTHON
aaa likes to read
C++
PYTHON
zzz
likes to read
PYTHON
ttt likes to read
*
������� variable-length arguments
def fun(name, *subj):
print("\n",name, "likes to read")
for i in subj:
print(i)
name1="xxx"
name2="aaa"
name3="yyy"
name4="www"
s1="C"
s2="JAVA"
s3="PYTHON"
fun(name1,s1,s2,s3)
fun(name2,s2,s1)
fun(name3,s2)
fun(name4)
*
������� variable-length arguments
def fun(name, *subj,str, x):
print("\n",name, "likes to read")
for i in subj:
print(i)
print("in semester",str,"in",x,"days")
name1="xxx"
name2="aaa"
name3="yyy"
name4="www"
s1="C"
s2="JAVA"
s3="PYTHON"
fun(name1,s1,s2,s3,str="VI",x=30)
fun(name2,s2,s1,str="VI",x=30)
fun(name3,s2,str="VI",x=30)
fun(name4,str="VI",x=30)
*
������� variable-length arguments
def fun(name, *subj,str, x):
print("\n",name, "likes to read")
for i in subj:
print(i)
print("in semester",str,"in",x,"days")
name1="xxx"
s1="C"
s2="JAVA"
s3="PYTHON"
str="VI"
x=30
fun(name1,s1,s2,s3,str,x)
O/P:
Traceback (most recent call last):
File "C:/Users/user/AppData/Local/Programs/Python/Python37-32/fun1.py", line 13, in <module>
fun(name1,s1,s2,s3,str,x)
TypeError: fun() missing 2 required keyword-only arguments: 'str' and 'x'
*
������� variable-length arguments
def fun(name, *subj,str, x):
print("\n",name, "likes to read")
for i in subj:
print(i)
print("in semester",str,"in",x,"days")
name1="xxx"
s1="C"
s2="JAVA"
s3="PYTHON"
str="VI"
x=30
fun(name1,s1,s2,s3,str=str,x=x)
O/P:
xxx likes to read
C
JAVA
PYTHON
in semester VI in 30 days
*
Lambda functions or Anonymous Functions
Syntax of Lambda Function in python
lambda arguments: expression
Lambda functions can have any number of arguments but only one expression. The expression is evaluated and returned. Lambda functions can be used wherever function objects are required.
*
# Program to show the use of lambda functions
double = lambda x: x * 2
print(double(5))
Output:
10
def double(x):
return x * 2
*
������� Lambda functions or Anonymous Functions
Lambda functions contain only a single line.
sum=lambda x, y : x + y
print(“sum=“,sum(3,5))
lambda x, y : x + y
is same as,
def sum(x,y):
return x+y
*
������� Lambda functions or Anonymous Functions
*
lambda function can access global variable�
c1=100
def sum2(n1,n2):
global c1
c1=300
�sum2(34,45)
sum1=lambda a,b:a+b*c1
print(sum1(5,8))
Output:
2405
*
����# lambda function can be passed as �arguments�
sq=lambda a:a*a
cu=lambda b:b*b*b
def sum1(s1,s2):
return s1+s2
ans=sum1(sq(5),cu(5))
�print(ans)
*
# using lambda functions inside a function�
def test1(a):
return (lambda a:a*a)(a)
print(test1(10))
Output: 100
(lambda a,b:a+b)(3,4)
print((lambda a,b:a+b)(3,4))
*
# sum of first 10 natural numbers using lambda funcitons with out arguments�
x=lambda:sum(range(1,11))
print(x())
output:
55
# sum of first 10 natural numbers using lambda funcitons
*
������� Lambda functions or Anonymous Functions
def small(a,b):
if a < b:
return a
else:
return b
sum=lambda x, y : x+y
diff=lambda x, y : x-y
print("smaller of two operations is",small(sum(-3,-2),diff(-1,2)))
O/P:
smaller of two operations is -5
*
������� Lambda functions or Anonymous Functions
def inc(a):
return (lambda i :i+1)(a)
n=int(input("enter a number"))
print("value of n is",n)
b=inc(n)
print("value of b is",b)
O/P:
enter a number6
value of n is 6
value of b is 7
*
������� Lambda functions or Anonymous Functions
print((lambda i :i*2)(7))
O/P:
14
#passes lambda function as argument to a function
def fun(f,n):
print(f(n))
twice=lambda x:x*2
thrice=lambda x:x*3
fun(twice,4)
fun(thrice,6)
O/P:
8
18
*
������� Lambda functions or Anonymous Functions
# sum of first 10 natural numbers
x=lambda:sum(range(1,11))
print(x())
O/P:
55
#lambda function that calls another lambda function
add=lambda x,y:x+y
mul_and_add=lambda x,y,z:x*add(y,z)
print(mul_and_add(3,4,5))
O/P:
27
*
������� Documentation Strings
def functionname(parameters);
“function_docstring”
function statements
return[expression]
*
# documentation strings�
def sum1(a,b):
" sum of two numbers“ #documentation string
print(sum1.__doc__)
return (a+b)
sum1(5,8)
*
������� Documentation Strings
def fun():
""“The program just prints the message.
It will display hello world!!! """
print("hello world")
print(fun.__doc__)
fun()
O/P:
the program just prints the message.
it will display hello world!!!
hello world
*
def sum1(a,b):
' sum of two numbers‘ #documentation
print(sum1.__doc__)
return (a+b)
sum1(5,8)
Output:
sum of two numbers
13
*
*
������� Recursive Functions
*
������� Factorial of a given number
n! = n * (n-1)!
For example, to find 5!
5 * 4!
4 * 3!
3 * 2!
2 * 1!
Base case
if n=1, result is 1, because 1!=1
Recursive case
fact(n)=n * fact(n-1)
*
������� Factorial of a given number
def fact(n):
if(n==1 or n==0):
return 1
else:
return n*fact(n-1)
n=int(input("enter a number"))
print("The factorial of", n,"is",fact(n))
O/P:
enter a number 5
The factorial of 5 is 120
*
# 1+2+3..�
# sum(5)=5+sum(4)
#sum(4)=4+sum(3)
�def sum(n):
if(n==0):
return 0;
else:
ans=n+sum(n-1)
return ans
n=int(input("enter a number"))
sum(n)
*
������� Greatest Common Divisor
Euclid’s algorithm is based on applying repeatedly the equality
gcd(m, n) = gcd(n, m mod n),
For example, gcd(60, 24) can be computed as follows:
gcd(60, 24) = gcd(24, 12) = gcd(12, 0) = 12.
Euclid’s algorithm for computing gcd(m, n)
Step 1 If n = 0, return the value of m as the answer and stop; otherwise,
proceed to Step 2.
Step 2 Divide m by n and assign the value of the remainder to r.
Step 3 Assign the value of n to m and the value of r to n. Go to Step 1.
Base case
if m%n == 0, return n
Recursive case
gcd(m, n) = gcd(n, m mod n)
*
������� Greatest Common Divisor
def gcd(a,b):
if(a%b==0):
return b
else:
return gcd(b,a%b)
a=int(input("enter a number:"))
b=int(input("enter a number:"))
print("GCD of", a, b,"is",gcd(a,b))
O/P:
enter a number:62
enter a number:8
GCD of 62 8 is 2
*
������� Finding Exponent
To find xy
For example, 23 can be computed as follows:
23 = 2 * 22
= 2 * 2 * 21
= 2 * 2 * 2 * 20
= 2 * 2* 2*1
= 8
Base case
if y==0, return 1
Recursive case
exp(x,y)= x* exp(xy-1)
*
������� Finding Exponent
def exp(x,y):
if(y==0):
return 1
else:
return x*exp(x,y-1)
x=int(input("enter a number"))
y=int(input("enter a number"))
print(x,"power", y,"is",exp(x,y))
O/P:
enter a number2
enter a number3
2 power 3 is 8
*
������� Fibonacci series
0 1 1 2 3 5 8 13 21 …….
Base case
if n==1, return 0
if n==2, return 1
Recursive case
fib(n-1)+fib(n-2)
*
������� Fibonacci series
def fib(n):
if(n==1):
return 0
elif(n==2):
return 1
else:
return fib(n-1)+fib(n-2)
n=int(input("enter the number of terms"))
for i in range(1,n+1):
print("Fibonacci(",i,")=",fib(i))
O/P:
enter the number of terms 5
Fibonacci( 1 )= 0
Fibonacci( 2 )= 1
Fibonacci( 3 )= 1
Fibonacci( 4 )= 2
Fibonacci( 5 )= 3
������� Recursion vs Iteration
Recursion
Follows top-down approach to solve a problem
Original problem is divided into smaller sub-problems
Iteration
Follows bottom-up approach to solve a problem
Begins the solution with what is known and then constructs the solution step-by-step
*
������� Pros and Cons
*
������� program to count number of times a recursive function is called
def fun(n, count=1):
if(n==1):
return count
else:
return fun(n-1, count+1)
n=int(input("enter a number"))
print("number of times recursive function was invoked",fun(n))
O/P:
enter a number100
number of times recursive function was invoked 100
������� Infinite Recursion
def fun(n, count=1):
if(n==1):
return count
else:
return fun(n, count+1)
n=int(input("enter a number"))
print("number of times recursive function was invoked",fun(n))
O/P:
enter a number2
Traceback (most recent call last):
File "C:/Users/user/AppData/Local/Programs/Python/Python37-32/fun2.py", line 7, in <module>
print("number of times recursive function was invoked",fun(n))
File "C:/Users/user/AppData/Local/Programs/Python/Python37-32/fun2.py", line 5, in fun
return fun(n, count+1)
File "C:/Users/user/AppData/Local/Programs/Python/Python37-32/fun2.py", line 5, in fun
return fun(n, count+1)
File "C:/Users/user/AppData/Local/Programs/Python/Python37-32/fun2.py", line 5, in fun
return fun(n, count+1)
[Previous line repeated 990 more times]
File "C:/Users/user/AppData/Local/Programs/Python/Python37-32/fun2.py", line 2, in fun
if(n==1):
RecursionError: maximum recursion depth exceeded in comparison
Thank you