updating a variable / scope problem

Rajarshi Guha rajarshi at presidency.com
Thu Jul 8 16:08:51 EDT 2004


Hi,
  I have been translating some Algol code to python and am facing a
problem. Heres an example of the code:

def f(x):

    print 'hello'
    c  =0

    def g(y):
        print c
        print 'bye'
    
    g(10)

if __name__ == "__main__":
    f(5)

The output is:

hello
0
bye

However when I edit the code so that I now have:

def f(x):

    print 'hello'
    c  =0

    def g(y):
        print c
        c = c + 1
        print 'bye'
    
    g(10)

if __name__ == "__main__":
    f(5)

running it gives me an error:

hello
Traceback (most recent call last):
  File "x.py", line 14, in ?
    f(5)
  File "x.py", line 11, in f
    g(10)
  File "x.py", line 7, in g
    print c
UnboundLocalError: local variable 'c' referenced before assignment

Now, I expected that since c is defined in the caller routine (ie f()) and
g() lies in the scope of f(), g() should be able to access c.

So which scope is c local to in this example? And why should'nt I be able
to increment c (rather - how do I do it)

Thanks,
Rajarshi




More information about the Python-list mailing list