Search code examples
pythonpython-3.xvariablesvariable-assignment

Python mixing global and local variable?


I initialize a global variable 'i' to 0 and a function definition. In the def, I want to initialize local 'j' to global 'i' and then assign 1 to global 'i', but the compliler thinks when I assign 1 to 'i', I initialize it.

this is not working:

i = 0
def doSomething():
    j = i # compiler throws UnboundLocalError here
    i = 1

and this is working:

i = 0
def doSomething():
    j = i

Solution

  • You need to declare the global variable within the function before modifying.

     i = 0
    def doSomething():
        global i #needed to modify the global variable.
        j = i # compiler throws UnboundLocalError here
        i = 1