updating a variable / scope problem

R

Rajarshi Guha

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top