Advance
Functions in
Python
Criteria to Create Closures in Python
• Nested Function
• Nested Function must refer values in enclosing scope
• Enclosing function must return nested function
Advantages of Closures in Python
• Can avoid Global Values
• Provides some kind of data Hiding Capabilities
Decorators
• Decoration to make more presentable / attractive
• Python Decorators
• Any callable python object that is used to modify a function or class
• It will take a function and it will add some functionality to it and will return
Two Types – Function Decorator and Class Decorator
Functions as Parameters to another function
def f1():
print(“Welcome to Function f1")
def f2(myf1):
print(“Welcome to Function f2")
f1()
f2(f1)
EX : def deco_upper(f1):
def inner_f():
mystr=f1()
return mystr.upper()
return inner_f
def disp_str():
return("welcome to
decoration ")
show_str=deco_upper(di
sp_str) print(show_str())
Ex: def show():
print("Ganesh")
#show()
def decorate(f):
def inner1():
print('---------')
f()
print('---------')
return inner1
x=decorate(show)
x()
def decorate_string(f1):
def inner():
str1=f1()
return str1.upper()
return inner
@decorate
_string def
show_string():
return
"Good
Morning"
print(show
_string())
• # Decorate function with Parameters
def decorate_div(f1):
def inner(x,y):
if y==0:
return "Invalid Input ....."
return f1(x,y)
return inner
@decor
ate_div def
div(a,b):
r
eturn
a/b
• For Decorator Functions
1. Need to take function as parameter
2. Add Functionality to function
3. Return another function
Multiple Decorators on single Function
# 2 decorator functions for a function
def convert_upper(f1):
def inner():
mystr=f1()
return
mystr.upper
()
return inner
def split_str(f1):
def inner():
str1=f1()
return
str1.split()
return inner
@split_str
@convert_upper
def show_str():
ret
ur
n
"G
oo
d
Mo
# Parameter [Passing for decorator function
def main_function(s): # Outer function with
Paramater def convert_upper(f1):
def inner():
mystr=f1()
return mystr.upper() + s
return inner
return convert_upper
@main_function(" Ganesh ") # Call decorator function with
parameter def show_str():
return " Good Morning "
print(show_str())
# Genaral Decorator function for multiple functions
def general_decorator_f(f): # General decorator function
def inner(*args):
L1=[]
L1=args[1:]
for i in L1:
if i==0:
return "Zero in
Denomin
ator....inv
alid!!!"
return f(*args)
return inner
@general_decorator_f
def divide_f1(x,y):
return x/y
@general_decorator_f
def divide_f2(x,y,z):
return x/y/z
print(divide_f1(10,0))
Map / Filter / Reduce
Lambda Functions
Lambda Functions
• Functions defined without a name
• Also called as anonymous function
• Lambda functions does not contain any def keyword
• Syntax :
lambda args : expression
Returns function object
def add(x,y):
return x+y
res=add(10,290)
print(type(res)) # return is int object
print(res)
r1=lambda x,y : x+y
print(type(r1)) # Return is function object
print(r1(10,290))
Map() function
• Built in function
• Used to apply a function to all the elements of a sequence
• Syntax :
map(function,sequence)
Ex : To find all the squares of numbers in the given list of elements
# 1 Code for printing squares of numbers in list
mylist=[x for x in range(1,10)]
print(mylist)
new=[]
for item in mylist:
new.append(ite
m**2)
print(new)
#map()
# to print squares of numbers in list
#1
nos_list=[x for x in range(1,5)]
print(nos_list)
#2
sq_nos_list=[x*x for x in range(1,5)]
print(sq_nos_list)
#3
for i in nos_list:
print(i*i)
#4 Using Function
def square(n):
return(n*
n)
for i in nos_list:
square(i)
#4 Using Map function
L1=list(map(square,nos_list))
print(L1)
• Note : map function
returns list in python 2
#5 Using Lambda function
s=tuple(map(lambda x:x*x,nos_list))
print(s)
# Adding two Lists using map
nos2_list=[x for x in range(5,9)]
print(nos2_list)
newlist=tuple(map(lambda x,y:x+y,nos_list,nos2_list))
print(newlist)
# 2 Second Method -- using function
mylist=[x for x in range(1,5)]
print(mylist)
def sq(n):
return n**2
s=list(map(sq,mylist))
print(s)
filter() Function
• This function will filter the elements of the iterables based on some
function
• Used to filter the / some unwanted elements
• Python3 returns the filter object
• Python2 returns the output in the list form
• Syntax :
filter(function,iterables)
# filter function
# Ex : to print all the even numbers from list
# 1 method
for i in range(1,11):
if i%2==0:
print(i)
#2 method
list1=[x for x in range(1,11) if x%2==0]
print(list1)
# 3 Using filter function filter() functions are faster
L1=list(filter(lambda x:x%2==0,range(1,11)))
print(L1)
L2=tuple(filter(lambda x:x%2==0,range(1,11)))
print(L2)
reduce() Function
• This reduce function will reduce a iterable to single element
using some functions
Output from reduce function will be single element
To perform some computation on list or tuples etc
we use reduce function
Function can be applied only on one iterable
Syntax :
reduce(function,iterable)
In Python3 – import functools
# Reduce function
# To find the sum of all elements in list
#1 method
numlist=[x for x in range(1,6)]
print(numlist)
s=0
for i in numlist:
s=s+i
print("sum ",s)
#2 method
from functools
import reduce
s=reduce(lambda x,y:x+y,numlist)
print(type(s))
print(s)
#3 method
def ret_sum(m,n):
return m+n
x=reduce(ret_sum,numlist)
print("last ",x)

Python_Functions_Advanced3_KMSolutions.pptx

  • 1.
  • 2.
    Criteria to CreateClosures in Python • Nested Function • Nested Function must refer values in enclosing scope • Enclosing function must return nested function Advantages of Closures in Python • Can avoid Global Values • Provides some kind of data Hiding Capabilities
  • 3.
    Decorators • Decoration tomake more presentable / attractive • Python Decorators • Any callable python object that is used to modify a function or class • It will take a function and it will add some functionality to it and will return Two Types – Function Decorator and Class Decorator
  • 4.
    Functions as Parametersto another function def f1(): print(“Welcome to Function f1") def f2(myf1): print(“Welcome to Function f2") f1() f2(f1)
  • 5.
    EX : defdeco_upper(f1): def inner_f(): mystr=f1() return mystr.upper() return inner_f def disp_str(): return("welcome to decoration ") show_str=deco_upper(di sp_str) print(show_str())
  • 6.
    Ex: def show(): print("Ganesh") #show() defdecorate(f): def inner1(): print('---------') f() print('---------') return inner1 x=decorate(show) x()
  • 7.
    def decorate_string(f1): def inner(): str1=f1() returnstr1.upper() return inner @decorate _string def show_string(): return "Good Morning" print(show _string())
  • 8.
    • # Decoratefunction with Parameters def decorate_div(f1): def inner(x,y): if y==0: return "Invalid Input ....." return f1(x,y) return inner @decor ate_div def div(a,b): r eturn a/b
  • 9.
    • For DecoratorFunctions 1. Need to take function as parameter 2. Add Functionality to function 3. Return another function
  • 10.
    Multiple Decorators onsingle Function # 2 decorator functions for a function def convert_upper(f1): def inner(): mystr=f1() return mystr.upper () return inner def split_str(f1): def inner(): str1=f1() return str1.split() return inner @split_str @convert_upper def show_str(): ret ur n "G oo d Mo
  • 11.
    # Parameter [Passingfor decorator function def main_function(s): # Outer function with Paramater def convert_upper(f1): def inner(): mystr=f1() return mystr.upper() + s return inner return convert_upper @main_function(" Ganesh ") # Call decorator function with parameter def show_str(): return " Good Morning " print(show_str())
  • 12.
    # Genaral Decoratorfunction for multiple functions def general_decorator_f(f): # General decorator function def inner(*args): L1=[] L1=args[1:] for i in L1: if i==0: return "Zero in Denomin ator....inv alid!!!" return f(*args) return inner @general_decorator_f def divide_f1(x,y): return x/y @general_decorator_f def divide_f2(x,y,z): return x/y/z print(divide_f1(10,0))
  • 13.
    Map / Filter/ Reduce
  • 14.
  • 15.
    Lambda Functions • Functionsdefined without a name • Also called as anonymous function • Lambda functions does not contain any def keyword • Syntax : lambda args : expression Returns function object
  • 16.
    def add(x,y): return x+y res=add(10,290) print(type(res))# return is int object print(res) r1=lambda x,y : x+y print(type(r1)) # Return is function object print(r1(10,290))
  • 17.
    Map() function • Builtin function • Used to apply a function to all the elements of a sequence • Syntax : map(function,sequence) Ex : To find all the squares of numbers in the given list of elements
  • 18.
    # 1 Codefor printing squares of numbers in list mylist=[x for x in range(1,10)] print(mylist) new=[] for item in mylist: new.append(ite m**2) print(new)
  • 19.
    #map() # to printsquares of numbers in list #1 nos_list=[x for x in range(1,5)] print(nos_list) #2 sq_nos_list=[x*x for x in range(1,5)] print(sq_nos_list) #3 for i in nos_list: print(i*i)
  • 20.
    #4 Using Function defsquare(n): return(n* n) for i in nos_list: square(i) #4 Using Map function L1=list(map(square,nos_list)) print(L1) • Note : map function returns list in python 2 #5 Using Lambda function s=tuple(map(lambda x:x*x,nos_list)) print(s)
  • 21.
    # Adding twoLists using map nos2_list=[x for x in range(5,9)] print(nos2_list) newlist=tuple(map(lambda x,y:x+y,nos_list,nos2_list)) print(newlist)
  • 22.
    # 2 SecondMethod -- using function mylist=[x for x in range(1,5)] print(mylist) def sq(n): return n**2 s=list(map(sq,mylist)) print(s)
  • 23.
    filter() Function • Thisfunction will filter the elements of the iterables based on some function • Used to filter the / some unwanted elements • Python3 returns the filter object • Python2 returns the output in the list form • Syntax : filter(function,iterables)
  • 24.
    # filter function #Ex : to print all the even numbers from list # 1 method for i in range(1,11): if i%2==0: print(i) #2 method list1=[x for x in range(1,11) if x%2==0] print(list1) # 3 Using filter function filter() functions are faster L1=list(filter(lambda x:x%2==0,range(1,11))) print(L1) L2=tuple(filter(lambda x:x%2==0,range(1,11))) print(L2)
  • 25.
    reduce() Function • Thisreduce function will reduce a iterable to single element using some functions Output from reduce function will be single element To perform some computation on list or tuples etc we use reduce function Function can be applied only on one iterable Syntax : reduce(function,iterable) In Python3 – import functools
  • 26.
    # Reduce function #To find the sum of all elements in list #1 method numlist=[x for x in range(1,6)] print(numlist) s=0 for i in numlist: s=s+i print("sum ",s) #2 method from functools import reduce s=reduce(lambda x,y:x+y,numlist) print(type(s)) print(s)
  • 27.
    #3 method def ret_sum(m,n): returnm+n x=reduce(ret_sum,numlist) print("last ",x)