Search code examples
python-3.xfunctionglobal-variablespython-3.6local-variables

Global and Local Variables in Python3


I am having trouble with Global Variables. I am trying to create a variable, change it, print it, change it again and print it again. However, I get an error even though my variables are already defined as Global. Why is this?

myGlobal = 5

def func1():
    global myGlobal
    myGlobal = 42
    func2()

def func2():
    print (myGlobal)
    myGlobal = myGlobal - 10
    print (myGlobal)

func1()

UnboundLocalError: local variable 'myGlobal' referenced before assignment


Solution

  • Here is your fixed code:

    myGlobal = 5
    
    def func1():
        global myGlobal
        myGlobal = 42
        func2()
    
    def func2():
        global myGlobal
        print (myGlobal)
        myGlobal = myGlobal - 10
        print (myGlobal)
    
    func1()
    

    What you are doing wrong is that you made myGlobal a global variable for func1 but not for func2, You are supposed to make it global there as well if you want to use it. It's not so that if you make it global in func1 then it's global for func2 also, for every function it's needed to be made global or else it will work as a local variable, but since it's not even defined as a local one so it's giving error. Hope it help you.