The Wayback Machine - https://web.archive.org/web/20240815151804/https://www.geeksforgeeks.org/assign-function-to-a-variable-in-python/
Open In App

Assign Function to a Variable in Python

Last Updated : 03 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

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

# calling the variable
var()

Output: 

GFG

The following programs will help you understand better:

Example 1: 

Python
# defined function
x = 123

def sum():
    x = 98
    print(x)
    print(globals()['x'])


# drivercode
print(x)

# assigning function
z = sum

# invoke function
z()
z()

Output:

123
98
123
98
123

Example 2: parameterized function

Python
# 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)

Output:

odd number
even number
odd number

Example 3:

Python
# 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))

Output:

240
400
4000

Assign Function to a Variable in Python – FAQs

How to set a function as a variable?

You can set a function as a variable by assigning the function to a variable name without calling it (i.e., without parentheses).

Example:

def greet():
print("Hello, World!")

# Assigning the function to a variable
greeting = greet

# Calling the function using the new variable
greeting() # Output: Hello, World!

How to store a function in a variable in Python?

To store a function in a variable, simply assign the function to the variable without using parentheses.

Example:

def add(a, b):
return a + b

# Storing the function in a variable
operation = add

# Using the variable to call the function
result = operation(5, 3)
print(result) # Output: 8

Can a function change a variable in Python?

Yes, a function can change a variable in Python if the variable is mutable (e.g., lists, dictionaries). For immutable types (e.g., integers, strings), the function can modify the variable locally, but it won’t change the original variable outside the function unless you return and reassign it.

Example with a mutable type:

def modify_list(my_list):
my_list.append(4)

nums = [1, 2, 3]
modify_list(nums)
print(nums) # Output: [1, 2, 3, 4]

Example with an immutable type:

def increment(x):
x += 1
return x

num = 10
num = increment(num)
print(num) # Output: 11

Can a function be assigned to another variable?

Yes, a function can be assigned to another variable, and the new variable can be used to call the function.

Example:

def multiply(a, b):
return a * b

# Assigning the function to another variable
product = multiply

# Using the new variable to call the function
result = product(5, 4)
print(result) # Output: 20

Previous Article
Next Article

Similar Reads

How to Fix "Can't Assign a numpy.ndarray to a torch.FloatTensor"?
The error "Can't assign a numpy.ndarray to a torch.FloatTensor" occurs when you attempt to assign a NumPy array to a PyTorch tensor directly, which is not allowed. PyTorch and NumPy are different libraries with different data structures, so you need to convert between them properly. Here's how you can fix this issue. Understanding the ProblemThe ro
4 min read
Pandas DataFrame assign() Method | Create new Columns in DataFrame
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, making importing and analyzing data much easier. The Dataframe.assign() method assigns new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original one
4 min read
How to detect whether a Python variable is a function?
There are times when we would like to check whether a Python variable is a function or not. This may not seem that much useful when the code is of thousand lines and you are not the writer of it one may easily stuck with the question of whether a variable is a function or not. We will be using the below methods to check the same. By calling the bui
3 min read
How to Use a Variable from Another Function in Python
Using a variable from another function is important for maintaining data consistency and code reusability. In this article, we will explore three different approaches to using a variable from another function in Python. Use a Variable from Another Function in PythonBelow are the possible approaches to using a variable from another function in Pytho
2 min read
Python | Set 6 (Command Line and Variable Arguments)
Previous Python Articles (Set 1 | Set 2 | Set 3 | Set 4 | Set 5) This article is focused on command line arguments as well as variable arguments (args and kwargs) for the functions in python. Command Line Arguments Till now, we have taken input in python using raw_input() or input() [for integers]. There is another method that uses command line arg
2 min read
__name__ (A Special variable) in Python
Since there is no main() function in Python, when the command to run a python program is given to the interpreter, the code that is at level 0 indentation is to be executed. However, before doing that, it will define a few special variables. __name__ is one such special variable. If the source file is executed as the main program, the interpreter s
2 min read
Python | setting and retrieving values of Tkinter variable
Tkinter supports some variables which are used to manipulate the values of Tkinter widgets. These variables work like normal variables. set() and get() methods are used to set and retrieve the values of these variables. The values of these variables can be set using set() method or by using constructor of these variables.There are 4 tkinter variabl
3 min read
Protected variable in Python
Prerequisites: Underscore ( _ ) in Python A Variable is an identifier that we assign to a memory location which is used to hold values in a computer program. Variables are named locations of storage in the program. Based on access specification, variables can be public, protected and private in a class. Protected variables are those data members of
2 min read
Python Program to swap two numbers without using third variable
Given two variables n1 and n2. The task is to swap the values of both the variables without using third variable.Examples: X : 10 Y : 20 After swapping X and Y, we get : X : 20 Y : 10 A : 'Hello' B : 'World' After swapping A and B, we get : A : 'World' B : 'Hello' Method 1 :- Using simple built-in method left , right = right , left This method work
4 min read
__file__ (A Special variable) in Python
A double underscore variable in Python is usually referred to as a dunder. A dunder variable is a variable that Python has defined so that it can use it in a "Special way". This Special way depends on the variable that is being used. Note: For more information, refer to Dunder or magic methods in Python The __file__ variable: __file__ is a variable
2 min read
Full domain Hashing with variable Hash size in Python
A cryptographic hash function is a special class of hash function that has certain properties which make it suitable for use in cryptography. It is a mathematical algorithm that maps data of arbitrary size to a bit string of a fixed size (a hash function) which is designed to also be a one-way function, that is, a function which is infeasible to in
5 min read
Pad or fill a string by a variable in Python using f-string
f-string stands for formatted string. It had come up by Python Version 3.6 and rapidly used to do easy formatting on strings. F-string is a string literal having syntax starts with f and followed by {}. That placeholder used for holding variable, that will be changed upon the variable names and their values respectively. There are already strings f
4 min read
PYTHONPATH Environment Variable in Python
Python's behavior is greatly influenced by its environment variables. One of those variables is PYTHONPATH. It is used to set the path for the user-defined modules so that it can be directly imported into a Python program. It is also responsible for handling the default search path for Python Modules. The PYTHONPATH variable holds a string with the
2 min read
Unused local variable in Python
A variable defined inside a function block or a looping block loses its scope outside that block is called ad local variable to that block. A local variable cannot be accessed outside the block it is defined. Example: C/C++ Code # simple display function def func(num): # local variable a = num print("The number is :", str(a)) func(10) # g
4 min read
Unused variable in for loop in Python
Prerequisite: Python For loops The for loop has a loop variable that controls the iteration. Not all the loops utilize the loop variable inside the process carried out in the loop. Example: C/C++ Code # i,j - loop variable # loop-1 print("Using the loop variable inside :") # used loop variable for i in range(0, 5): x = (i+1)*2 print(x, en
3 min read
Python - Iterate through list without using the increment variable
Python Lists is much like flexible size arrays, declared in other languages like vector in C++, array list in Java, etc. Lists are heterogeneous, making it the most effective feature in Python. Lists are mutable, and hence can be modified even after they have been formed. The most common approach is to iterate through a list using the increment var
2 min read
Python - Solve the Linear Equation of Multiple Variable
Prerequisite: Sympy.solve() In this article, we will discuss how to solve a linear equation having more than one variable. For example, suppose we have two variables in the equations. Equations are as follows: x+y =1 x-y =1 When we solve this equation we get x=1, y=0 as one of the solutions. In Python, we use Eq() method to create an equation from
2 min read
Create integer variable by assigning binary value in Python
Given a binary value and our task is to create integer variables and assign values in binary format. To assign value in binary format to a variable, we use the 0b suffix. It tells the compiler that the value (suffixed with 0b) is a binary value and assigns it to the variable. Input: Var = 0b1010 Output: 10 Input: Var = 0b11001 Output: 25 Note: To p
2 min read
Exporting variable to CSV file in Python
The CSV file or comma-separated values file is used to store and share data across platforms. The columns are separated by commas or other relevant delimiters, giving the data a tabular structure. Sometimes we come across ready-made CSV files while sometimes we need to create one according to the requirements in our projects. Python can write CSV f
3 min read
Python - Find text using beautifulSoup then replace in original soup variable
Python provides a library called BeautifulSoup to easily allow web scraping. BeautifulSoup object is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. The BeautifulSoup object represents the parsed document as a w
3 min read
Create Constant Variable in Python using Pconst Library
Constant variable the name itself says that it is constant. We have to define a constant variable at the time of declaration. After that, we will not able to change the value of a constant variable. In some cases, constant variables are very useful. Creating constant variables, functions, objects is allowed in languages like c++, Java. But in pytho
2 min read
Python Program to Find and Print Address of Variable
In this article, we are going to see how to find and print the address of the Python variable. It can be done in these ways: Using id() functionUsing addressof() functionUsing hex() functionMethod 1: Find and Print Address of Variable using id() We can get an address using id() function, id() function gives the address of the particular object. Syn
2 min read
Multiply a Hermite series by an independent variable in Python using NumPy
In this article, we are going to see how to multiply a Hermite series by an independent variable in Python Using NumPy. The NumPy method numpy.polynomial.hermite.hermmulx() is used to Multiply a Hermite series by x(independent variable) to get a new one. Let's understand the syntax to know more about the method. The Hermite series c is multiplied b
2 min read
Read a text file into a string variable and strip newlines in Python
It is quite a common requirement for users to remove certain characters from their text files while displaying. This is done to assure that only displayable characters are displayed or data should be displayed in a specific structure. This article will teach you how to read a text file into a string variable and strip newlines using Python. For dem
5 min read
Convert String into Variable Name in Python
There may be situations where you want to convert a string into a variable name dynamically. In this article, we'll explore how to convert a string into a variable name in Python with four simple examples. Convert String into Variable Name in PythonWhile Python does not directly allow you to convert a string into a variable name, these examples dem
3 min read
Variable Length Argument in Python
In this article, we will cover about Variable Length Arguments in Python. Variable-length arguments refer to a feature that allows a function to accept a variable number of arguments in Python. It is also known as the argument that can also accept an unlimited amount of data as input inside the function. There are two types in Python: Non - Keyword
4 min read
Access environment variable values in Python
An environment variable is a variable that is created by the Operating System. Environment variables are created in the form of Key-Value pairs. To Access environment variables in Python's we can use the OS module which provides a property called environ that contains environment variables in key-value pairs. In this article, we will see how to use
3 min read
Get Variable Name As String In Python
In Python, getting the name of a variable as a string is not as straightforward as it may seem, as Python itself does not provide a built-in function for this purpose. However, several clever techniques and workarounds can be used to achieve this. In this article, we will explore some simple methods to obtain the variable name as a string in Python
3 min read
How To Print A Variable's Name In Python
In Python, printing a variable's name can be a useful debugging technique or a way to enhance code readability. While the language itself does not provide a built-in method to directly obtain a variable's name, there are several creative ways to achieve this. In this article, we'll explore five simple methods to print a variable's name in Python. P
3 min read
Undefined Variable Nameerror In Python
Encountering the "NameError: name 'var' is not defined" is a common experience for Python users. In Python, variable declaration is a straightforward process of assigning a value. This error arises when attempting to access a non-existent variable or one not defined in the program. Surprisingly, it can occur even when the variable is present, owing
5 min read
Practice Tags :
three90RightbarBannerImg