Open In App

Assign Function to a Variable in Python

Last Updated : 15 Jul, 2025
Comments
Improve
Suggest changes
8 Likes
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:


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


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


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


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