Skip to content
Related Articles

Related Articles

Assign Function to a Variable in Python
  • Last Updated : 29 Dec, 2020

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



filter_none

edit
close

play_arrow

link
brightness_4
code

def a():
  print("GFG")
    
# assigning function to a variable
var=a
  
# calling the variable
var()

chevron_right


Output:

GFG

The following programs will help you understand better:

Example 1: 

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# defined function
x = 123
  
def sum():
    x = 98
    print(x)
    print(globals()['x'])
  
  
# drivercode
print(x)
  
# assigning function
z = sum
  
# invoke function
z()
z()

chevron_right


Output:

123
98
123
98
123

Example 2: parametrized function

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# function defined
def even_num(a):
    if a % 2 == 0:
        print("even number")
    else:
        print("odd number")
  
  
# drivercode
# assigning function
z = even_num
  
# invoke function with argument
z(67)
z(10)
z(7)

chevron_right


Output:

odd number
even number
odd number

Example 3:

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# function defined
def multiply_num(a):
    b = 40
    r = a*b
    return r
  
  
# drivercode
# assigning function
z = multiply_num
  
# invoke function
print(z(6))
print(z(10))
print(z(100))

chevron_right


Output:

240
400
4000

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :