-4

I'm a bit confused as to how Python's variable scope system works. Say I have situation like this:

a = 10
def test():
    print(a)

Then everything works just as I expect. Python first looks for a local variable a, fails to find it and then searches for a global variable.

However, in a situation like this:

a = 10
def test():
    print(a)
    a += 1
    print(a)

Python throws an UnboundLocalError exception, apparently originating from line 3 (print(a)). To me it seems that at least to this line nothing has changed, and I don't understand why there is an exception anyway.

Parzival
  • 95
  • 6

1 Answers1

0

Since python does not have variable declarations, every variable assignment inside the scope of a function is considered local. So, you always have to specify that that variable is a global one:

a = 10
def test():
    global a
    print(a)
    a += 1
    print(a)
test()
Ericson Willians
  • 7,606
  • 11
  • 63
  • 114