newbie
newbie

Reputation: 1571

Using variables from another function in a function

I have tried to search this but I don't quite understand. I am coming across this error so I formed a quick easy example.

def test():
    global a
    a = 0
    a+=1

def test2():
    a+=1
    print (a)


inp = input('a?')
if inp == 'a':
    test()
    test2()

When I input a. I expected the code to output 2. However, I get this error UnboundLocalError: local variable 'a' referenced before assignment. When I searched around about this, I found that you need to use global, but I already am using it.

So I don't understand. Can someone briefly explain what I'm doing wrong? Thanks.

Upvotes: 0

Views: 63

Answers (2)

destresa
destresa

Reputation: 117

1) You can return the modified value like:

def test():
    a = 0
    a+=1
    return a

def test2(a):
    a+=1
    print (a)


inp = input('a?')
if inp == 'a':
    a = test()
    test2(a)

2) Or you can use a class:

class TestClass:

    a = 0

    def test(self):
        self.a = 0
        self.a+=1

    def test2(self):
        self.a+=1
        print (self.a)

Usage of option 2:

>>> example = TestClass()
>>> example.test()
>>> example.test2()
2

Upvotes: 1

Barmar
Barmar

Reputation: 780724

A global declaration only applies within that function. So the declaration in test() means that uses of the variable a in that function will refer to the global variable. It doesn't have any effect on other functions, so if test2 also wants to access the global variable, you need the same declaration there as well.

def test2():
    global a
    a += 1
    print(a)

Upvotes: 1

Related Questions