Open In App

Assign Function to a Variable in Python

Last Updated : 26 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, functions are first-class objects, meaning they can be assigned to variables, passed as arguments and returned from other functions. Assigning a function to a variable enables function calls using the variable name, enhancing reusability.

Example:

Python
# defining a function
def a(): 
  print("GFG")
  
# assigning function to a variable
var=a

# calling the variable
var()

Output
GFG

Explanation: a() prints "GFG". It is assigned to var, which now holds a reference to a(). Calling var() executes a().

Implementation:

To assign a function to a variable, use the function name without parentheses (). If parentheses are used, the function executes immediately and assigns its return value to the variable instead of the function itself.

Syntax:

# Defining a function

def fun():

# Function body

pass

# Assigning function to a variable

var = fun

# Calling the function using the variable

var()

Example 1: Function with Local and Global Variables

Python
x = 123  # global variable

def display():
    x = 98  # local variable
    print(x)  
    print(globals()['x'])  # accesses global x

print(x) 

a = display  # assign function to a variable
a()  # call function
a()  # call function

Output
123
98
123
98
123

Explanation: Inside display(), local x = 98 is printed first, then global x = 123 using globals()['x']. The function is assigned to a, allowing display() to run twice via a().

Example 2: Assigning a Function with Parameters

Python
# defining a function
def fun(num):
    if num % 2 == 0:
        print("Even number")
    else:
        print("Odd number")

# assigning function to a variable
a = fun

# calling function using the variable
a(67)
a(10)
a(7)

Output
Odd number
Even number
Odd number

Explanation: fun(num) checks if num is even or odd and prints the result. It is assigned to a, allowing it to be called using a(num), which executes fun(num).

Example 3: Assigning a Function that Returns a Value

Python
# defining a function
def fun(num):
    return num * 40

# assigning function to a variable
a = fun

# calling function using the variable
print(a(6))
print(a(10))
print(a(100))

Output
240
400
4000

Explanation: function fun(num) returns num * 40. It is assigned to a, allowing a(num) to execute fun(num).


Next Article

Similar Reads