1

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
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • 2
    An assignment to a variable anywhere in a function body makes that variable *local* – juanpa.arrivillaga Jan 11 '19 at 00:06
  • I would paraphrase a title "Python mixing global and local variable?" to "Why is Python protecting from using a global and local variable?". The answer is "Because you shouldn't ". – Evgeny Jan 11 '19 at 00:09
  • 2
    Short answer, without explicit `global var`, `var` is readonly in local scope. – Sraw Jan 11 '19 at 00:11

1 Answers1

0

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
Mike C.
  • 1,761
  • 2
  • 22
  • 46