Pass function as an argument in Python
Python functions can take multiple arguments, these arguments can be variables, objects and functions.
Example to represent functions can be treated as objects
def display(text):
return text.upper()
print(display('Hello'))
show = display
print(show('Hello'))
Output of the above program is
HELLO
HELLO
Python Higher Order Function
Because functions are objects so we can pass them as arguments to other functions. Functions that can accept other functions as arguments called as higher order functions.
Example of higher order function
In this example, we will create meet() function which takes a function as an argument.
def show(text):
return text.upper()
def display(text):
return text.lower()
def meet(func):
# storing the function in a variable
greeting = func("This is created by a function passed as an argument.")
print(greeting)
meet(show)
meet(display)
Output of the above program is
THIS IS CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
this is created by a function passed as an argument.
Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments |
---|
No Content Found. |
Interview Questions & Answers |
---|
No Content Found. |