12.Functions
12.Functions
Ex :
def wish(name):
wish("gangadhar")
wish("lokesh")
Ex: def
happyBirthday(person):
print("Happy Birthday dear ",person)
def main():
happyBirthday('gangadhar')
happyBirthday('lokesh')
main()
a,b=10,20
sum=addition(a ,b)
print(sum)
Ex:
def big(a,b):
if a>b:
return a
else:
return b
print(big(10,20))
print(big(50,40))
Ex:
def cal(a,b):
sum=a+b
sub=a-b
mul=a*b
div=a/b
return sum,sub,mul,div
t=cal(10,2)
print("The results are:")
for i in t:
print(i)
If there is no expression in the statement or the return statement itself is not
present inside a function, then the function will return the None object.
Ex:
def wish(name):
print("Hello",name," Good morning")
wish("gangadhar")
wish("lokesh")
print(wish("ram"))
Types of arguments:
def f1(a,b):
-------
-------
f1(10,20)
a,b are formal arguments whereas 10,20 are actual arguments.
There are 4 types of actual arguments are allowed in Python.
1. Positional arguments.
2. Keyword arguments.
3. Default arguments.
4. Variable length arguments.
Positional arguments: - This is the default method. These are the arguments
passed to function in correct positional order.
Ex:
def cal(a,b):
s=a+b
return s
print(cal(100,10))
print(cal(100,100))
Ex:
def add(a,b):
print(a+b)
add(10,20)
add(10.5,20.4)
add("gangadhar","babu")
add(10,10.5)
add("gangadhar",10)
Keyword Arguments: - The keywords are mentioned during the function call
along with their corresponding values. These keywords are mapped with the
function arguments so the function can easily identify the corresponding values
even if the order is not maintained during the function call.
Using the Keyword Argument, the argument passed in function call is matched
with function definition on the basis of the name of the parameter.
Ex:
def cal(a,b,c):
s=a+b+c
return s
print(cal(c=33,a=23,b=55))
Ex:
def msg(id,name):
print(id,name)
msg(id=111,name='gangadhar')
msg(name='anu',id=222)
Ex:
def disp(eid,ename):
print(eid,ename)
disp(eid=111,ename="anu")
disp(ename="ratan",eid=222)
disp(333,"durga")
disp(444,ename="sravya")
disp(eid=555,"aaa")
#SyntaxError: positional argument follows keyword argument
Ex :
def empdetails(eid=1,ename="anu",esal=10000):
print ("Emp id =", eid)
print ("Emp name = ", ename)
print ("Empsal=", esal)
print("*********")
empdetails()
empdetails(222)
empdetails(333,"durga")
empdetails(111,"ratan",10.5)
ex :
def defArgFunc( empname, emprole = "Manager" ):
print ("Emp Name: ", empname)
print ("Emp Role ", emprole)
var-arg: -
var-arg means variable length argument.
Sometimes, we don’t know in advance the number of arguments that will be
passed into a function Python allows us to handle this type of situation
through function calls with arbitrary number of arguments.
In this function, we use “*” before the parameter. Ex:
def wish(*name):
for x in name:
print("Hello:",x)
wish('gangadhar', 'lokesh', 'rajesh')
Ex:
def disp(*var):
for i in var:
print("var arg=",i)
disp()
disp(10,20,30)
disp(10,20.3,"gangadhar")
Ex:
def sum(*a):
s=0
for x in a:
s=s+x
return s
print(sum(10,20))
print(sum(10,20,45,66))
print (sum())
We can mix positional arguments to var-arg
Ex:
def calc(x,*n):
s=0
for i in n:
s=s+i
print("x=",x,"sum=",s)
calc(10) calc(11,33,22,44,55))
Types of variables:
Global variables: - A variable which is declared outside of the function or in
global scope is known as global variable. That means, global variable can be
accessed inside or outside of the function.
Ex:
def wish():
print("Inner:",x)
x=10
wish()
print("Outer:",x)
Local variables: - A variable which is declared inside the function body or in
a local scope is known as local variables. These variables are accessed
within the function.
Ex:
def f1():
y=10
print("Inner=",y
) f1() print("outer=",y)
first("Hello")
s=first
s("Hai")
Recursive functions: -
A function called by itself is known as recursion.
It reduces length of the code and improves readability. We can solve complex
problems very easily.
Ex: Write a program for factorial of a given number
def fact(n): if n==0:
res=1
else: res=n*fact(n-1)
return res
print(fact(5)) print(fact(6))
Ex:
s=lambda n:n*n
print(s(4))
print(s(6))
def dec(x)
return(x-1)
def operate(func,x)
res=func(x)
return res
print(operate(inc,10))
print(operate(dec,20))
filter(): - This function takes a function and list as arguments. The function is
called with all the items in the list and new list is returned which contains
items for which the function evaluates true.
Syntax:
filter(function,sequence)
Ex:
def iseven(x):
if x%2==0:
return True
else:
return False
l=[10,8,5,12,13,11,10]
l2=list(filter(iseven,l))
print(l2)
Using lambda
l1=[10,8,5,12,13,11,10]
l2=list(filter(lambda x:x%2==0,l1))
print(l2)
map(): - This function takes a function and list as arguments. This function is
called with all the items in the list and a new list is returned which contains
items returned by that function for each item.
filter() and map() are same but filter() always displays checks True or False
but map() is used for business operations.
Syntax:
map(function,list)
Ex:
def square(x):
return x*x
l1=[10,8,5,12,13,11,10]
l2=list(map(square,l1))
print(l2)
with lambda
l1=[1,2,3,4,5]
l2=list(map(lambda x:x*x,l1))
print(l2)
Ex:
l1=[1,2,3,4]
l2=[10,20,30,40]
l3=list(map(lambda x,y:x*y,l1,l2))
print(l3)
reduce(): -
This function applies any sequence and returns a single value.
If sequence=[s1,s2,s3….sn], calling reduce as follows
At the first two elements of sequence will be applied to func, that is
func(s1,s2), the list on which reduce() works looks now like this
[func(s1,s2),s3…sn]
In the next step func will be applied on the previous result and the third
element of the list that is func(func(s1,s2),s3)
Continue like this until just one element is left and return this element as the
result reduce().
Syntax:
reduce(func,seq)
Ex:
from functools import reduce
print(reduce(lambda x,y:x+y,[45,66,77,88,99]))
45 66 77 88 99
111
188
276
375
Ex:
from functools import *
f=lambda a,b: a if a>b else b
print(reduce(f,[23,44,56,44,87,55]))
Ex:
from functools import *
print(reduce(lambda x,y:x+y,range(1,101)))