-1

I have a variable inside a function that I want to work inside another function. My code is this:

def my_function(self):
    my_variable = "hello world"
    print(my_variable)

def my_other_function(self):
    if my_variable == "hello world":
        print("pass")

And in the second function it tells me that the variable is undefined

Does anyone know how to make this variable work in other functions?

Sylvester Kruin
  • 3,294
  • 5
  • 16
  • 39
john eat
  • 3
  • 1
  • 3
  • 1
    To get something from a function, call it and retrieve the `return` value – azro Nov 11 '20 at 18:21
  • Does this answer your question? [How to Access Function variables in Another Function](https://stackoverflow.com/questions/32822473/how-to-access-function-variables-in-another-function) – Tomerikoo Nov 09 '21 at 22:27

2 Answers2

0

Normally we don't declare global variables inside functions in python. Even so, by using them, you can achieve what you want (make the variable work on both functions). Your code would look like that:

def my_function(self):
    global my_variable
    my_variable = "hello world"
    print(my_variable)

def my_other_function(self):
    if my_variable == "hello world":
        print("pass")

What I recommend you, though, is to return the variable you want on the first function and then use it on the second one.

In that case, the code would look like that:

def my_function():
    my_variable = "hello world"
    print(my_variable)
    return my_variable

def my_other_function():
    my_variable = my_function()
    if my_variable == "hello world":
        print("pass")
Mateus
  • 266
  • 1
  • 7
0

Given self argument you passed to your function, I assume you're dealing with classes. If that is the case, you could access that variable from self object.

class Foo:
    def __init__(self):
        self.my_variable = "foo"

    def my_function(self):
        self.my_variable = "hello world"

    def my_other_function(self):
        if self.my_variable == "hello world":
            print("pass")

my_class = Foo()
my_class.my_function()
my_class.my_other_function()

If you're not working with classes, the best way of doing this is returning your variable from your functions.

def my_function():
    my_variable = "hello world"

    return my_variable

def my_other_function():
    my_var = myfunction()
    if my_var == "hello world":
        print("pass")

You may also work with global variables. To do that you should define a variable outside your functions and tell python to refer the that variable.

my_variable = "foo"

def my_function():
    global my_variable

    my_variable = "hello world"
    

def my_other_function():
    global my_variable
    
    if my_variable == "hello world":
        print("pass")

Although it is very useful in scripting, it is not recommended to use big codes or applications.

Alisson Correa
  • 357
  • 2
  • 8