How to use a variable from another function python

One approach would be to make oneFunction return the word so that you can use oneFunction instead of word in anotherFunction :

def oneFunction(lists):
    category = random.choice(list(lists.keys()))
    return random.choice(lists[category])

    
def anotherFunction():
    for letter in oneFunction(lists):              
        print("_", end=" ")

Another approach is making anotherFunction accept word as a parameter which you can pass from the result of calling oneFunction:

def anotherFunction(words):
    for letter in words:              
        print("_", end=" ")
anotherFunction(oneFunction(lists))

And finally, you could define both of your functions in a class, and make word a member:

class Spam:
    def oneFunction(self, lists):
        category=random.choice(list(lists.keys()))
        self.word=random.choice(lists[category])

    def anotherFunction(self):
        for letter in self.word:              
            print("_", end=" ")

Once you make a class, you have to instantiate an instance and access the member functions:

s = Spam()
s.oneFunction(lists)
s.anotherFunction()

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")
    print(function_1.var)

function_1()
function_2()

Run this code online

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:

  • Classes and Objects in Python

How to use a variable from another function python

In Python and most programming languages, variables declared outside a function are known as global variables. You can access such variables inside and outside of a function, as they have global scope.

Here's an example of a global variable:

x = 10 

def showX():
    print("The value of x is", x)
    
showX()
# The value of x is 10

The variable x in the code above was declared outside a function: x = 10.

Using the showX() function, we were still able to access x because it was declared in a global scope.

Let's take a look at another example that shows what happens when we declare a variable inside a function and try to access it elsewhere.

def X():
    x = 10 

X()

def showX():
    print("The value of x is", x)
    
showX()
NameError: name 'x' is not defined

In the example above, we declared x inside a function and tried to access it in another function. This resulted in a NameError because x was not defined globally.

Variables defined inside functions are called local variables. Their value can only be used within the function where they are declared.

You can change the scope of a local variable using the global keyword – which we'll discuss in the next section.

What is the global Keyword Used for in Python?

The global keyword is mostly used for two reasons:

  • To modify the value of a global variable.
  • To make a local variable accessible outside the local scope.

Let's look at some examples for each scenario to help you understand better.

Example #1 - Modifying a Global Variable Using the global Keyword

In the last section where we declared a global variable, we did not try to change the value of the variable. All we did was access and print its value in a function.

Let's try and change the value of a global variable and see what happens:

x = 10 

def showX():
    x = x + 2
    print("The value of x is", x)
    
showX()
# local variable 'x' referenced before assignment

As you can see above, when we tried to add 2 to the value of x, we got an error. This is because we can only access but not modify x.

To fix that, we use the global variable. Here's how:

x = 10 

def showX():
    global x
    x = x + 2
    print("The value of x is", x)
    
showX()
# The value of x is 12

Using the global keyword in the code above, we were able to modify x and add 2 to its initial value.

Example #2 - How to Make a Local Variable Accessible Outside the Local Scope Using the global Keyword

When we created a variable inside a function, it wasn't possible to use its value inside another function because the compiler did not recognize the variable.

Here's how we can fix that using the global keyword:

def X():
    global x
    x = 10 
    
X()
    
def showX():
    print("The value of x is", x)
    
showX()
# The value of x is 10

To make it possible for x to be accessible outside its local scope, we declared it using the global keyword: global x.

After that, we assigned a value to x. We then called the function we used to declare it: X()

When we called the showX() function, which prints the value of x declared in the X() function, we did not get an error because x has a global scope.

Summary

In this article, we talked about global and local variables in Python.

The examples showed how to declare both global and local variables.

We also talked about the global keyword which lets you modify the value of a global variable or make a local variable accessible outside its scope.

Happy coding!



Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

How do you access a variable from another function in Python?

You need to declare the variable as global in the scope which it is used, which in this case is the function test() : def test(): global var var = "Hello!" Note that the final return is not necessary, since it is implicit at the end of a function.

Can you use a variable from one function in another 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.

How do you call a variable from one function to another?

You can use the function to set the value of a variable outside the context of the function, then you can use it as an argument in another function. You can use the function to set the value of a variable outside the context of the function, then you can use it as an argument in another function.

How do I use a variable from another class in Python?

Access one class variable in another class using inheritance in python. What is inheritance: Inheritance is an important topic of object-oriented programming language. Inheritance provides code reusability to the program because we can use an existing class to create a new class instead of creating it from scratch.