How to use a variable from another function in Python

In this article, we’ll discuss how to use a variable from another function in Python. In general, functions limit the scope of the variables to the function block and they cannot be accessed from outside the function.

Functions in Python:

Functions are treated as objects in Python. It means that they can be passed as arguments, assigned and stored in variables. It is also possible to associate variables with functions in Python. This is how we will approach the current task of accessing a variable from outside the function. This is done similar to how we access members of a class by their object using the “.” operator.

How to use a variable from another function in Python:

The variable can be assigned to the function object inside the function body. So the variable exists only after the function has been called. Once the function has been called, the variable will be associated with the function object. This variable can now be used anywhere inside or outside any function. Let’s see a sample implementation of the same in the below code.

def function_1():
    # assigning a string as a member of the function object
    function_1.var = "variable inside function_1"
    print("function_1 has been called")

def function_2():
    print("function_2 has been called")


Note that the function_1 has to be called first else the function_2 will access a variable that has not been created yet. Running the same code without the function_1() will result in an attribute error. The output for the above code is as follows:

function_1 has been called
function_2 has been called
variable inside function_1

The output clearly explains the flow of control inside the code. The function_2 accesses the attribute of function_1 which has to be called first. Therefore, I hope you found this article helpful in understanding how to access variables from another function in Python.

See also:

2 responses to “How to use a variable from another function in Python”

  1. Rahul tripathi says:

    Ahhh,,,,finally I got the solution for which I m struggling for last one hours.
    sites like this make coding a fun.
    lots of love to the site and best wishes too.

  2. Rajesh Kumar says:

    Thanks. Very well and neatly written. Other blogs/articles are slightly confusing and misleading. This is simple and up to the mark.

Leave a Reply

Your email address will not be published. Required fields are marked *