Functions are first-class objects, which means they can be assigned to variables just like any other value. Once a function is assigned to a variable, the function can be called using either the original function name or the variable.
def show():
print("GFG")
func = show
func()
Output
GFG
Explanation:
- show is a function that prints "GFG".
- func = show assigns the function reference to the variable func.
- Calling func() executes the show() function
Note: When assigning a function to a variable, use the function name without parentheses. Writing func = show assigns the function itself, while func = show() executes the function and assigns its return value.
Syntax
def function_name(parameters):
# function body
passvariable_name = function_name
variable_name(arguments)
Where:
- function_name is the name of the function.
- variable_name stores the reference to the function.
- variable_name(arguments) calls the function through the variable.
Examples
Example 1: The following example demonstrates assigning a function to a variable and calling it using that variable. It also shows the difference between local and global variables.
x = 123
def display():
x = 98
print(x)
print(globals()['x'])
print(x)
a = display
a()
a()
Output
123 98 123 98 123
Explanation:
- global variable x has the value 123. Inside display(), a local variable x with value 98 is created.
- globals()['x'] accesses the global variable x, a = display assigns the function to the variable a and calling a() executes the display() function.
Example 2: The following example assigns a function that accepts a parameter to a variable and calls it using that variable.
def check(num):
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
a = check
a(67)
a(10)
a(7)
Output
Odd number Even number Odd number
Explanation:
- check(num) determines whether a number is even or odd.
- a = check assigns the function to the variable a.
- Calling a(num) executes the check() function with the given argument.
Example 3: The following example assigns a function that returns a value to a variable and calls it using that variable.
def multiply(num):
return num * 40
a = multiply
print(a(6))
print(a(10))
print(a(100))
Output
240 400 4000
Explanation:
- multiply(num) returns num * 40 and a = multiply stores a reference to the function in a.
- Calling a(num) executes the function and returns the calculated value.