In this article, we are going to see how to assign a function to a variable in Python. In Python, we can assign a function to a variable. And using that variable we can call the function as many as times we want. Thereby, increasing code reusability.
Implementation
Simply assign a function to the desired variable but without () i.e. just with the name of the function. If the variable is assigned with function along with the brackets (), None will be returned.
Syntax:
def func():
{
..
}
var=func
var()
var()
Example:
Python3
def a():
print ( "GFG" )
var = a
var()
|
Output:
GFG
The following programs will help you understand better:
Example 1:
Python3
x = 123
def sum ():
x = 98
print (x)
print ( globals ()[ 'x' ])
print (x)
z = sum
z()
z()
|
Output:
123
98
123
98
123
Example 2: parameterized function
Python3
def even_num(a):
if a % 2 = = 0 :
print ( "even number" )
else :
print ( "odd number" )
z = even_num
z( 67 )
z( 10 )
z( 7 )
|
Output:
odd number
even number
odd number
Example 3:
Python3
def multiply_num(a):
b = 40
r = a * b
return r
z = multiply_num
print (z( 6 ))
print (z( 10 ))
print (z( 100 ))
|
Output:
240
400
4000
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!