0

What's the difference between doing:

m={}
i='a'

def change():
    m['a'] = i
    i = 'b'

Which raises an attribute error:

>>> change()

UnboundLocalError: local variable 'i' referenced before assignment

And:

m={}
i='a'

def change():
    m['a'] = i

Which evaluates without an error.

>>> change()
>>> m
{'a': 'a'}

(Finally, a question about this question -- when is it appropriate to use the "yellow background" in the questions?)

1 Answers1

0

This is answered in depth in the docs:

This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in foo assigns a new value to x, the compiler recognizes it as a local variable. Consequently when the earlier print(x) attempts to print the uninitialized local variable and an error results.

And the yellow background is stylistic but is generally used for quotes from somewhere but also can be used for any reason you want to break that text away from the main body or text or code.

MyNameIsCaleb
  • 4,409
  • 1
  • 13
  • 31