1

This code works as expected:

    def my_fun():
        a = b
        a = 5
        print a

    b = 2
    my_fun()
    print b

And I get:

5
2

But if I do:

    def my_fun():
        a = b
        a = 5
        b = 1
        print a

    b = 2
    my_fun()
    print b

I do get the error: UnboundLocalError: local variable 'b' referenced before assignment

What happens here ? Although b is visible to the function, I cannot change it inside the function ?

Moritz
  • 5,130
  • 10
  • 40
  • 81

1 Answers1

1

When you assign b = 1, the interpreter starts treating b as a local variable. If you want to assign the global variable b, you have to put the statement global b at the start of your function.

def my_fun():
    global b
    # do stuff

b = 2
my_fun()
print b
Fernando Matsumoto
  • 2,697
  • 1
  • 18
  • 24