◐ Shell
clean mode source ↗

Issue 972467: local variables problem

def test1():
    print a
    a += 1
                                                      
                                                      
                                               
a = 1
test1()


This results in a UnboundLocalError, while a is already
assigned

Traceback (most recent call last):
  File "bug.py", line 6, in ?
    test1()
  File "bug.py", line 2, in test1
    print a
UnboundLocalError: local variable 'a' referenced before
assignment
Logged In: YES 
user_id=31435

Not a bug.  Ask on comp.lang.python for an explanation, or 
read the docs more carefully.  Short course:  'a' is local in 
test1 because 'a' is assigned to in test1.  It has no relation 
to the global named 'a'.  If you want test1 to use the global 
named 'a', put

    global a

as the first line of test1.