updating a variable / scope problem

Discussion in 'Python' started by Rajarshi Guha, Jul 8, 2004.

  1. 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
     
    Rajarshi Guha, Jul 8, 2004
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Paul Opal
    Replies:
    12
    Views:
    1,002
    Paul Opal
    Oct 11, 2004
  2. Robert Brewer

    RE: updating a variable / scope problem

    Robert Brewer, Jul 8, 2004, in forum: Python
    Replies:
    1
    Views:
    295
    Duncan Booth
    Jul 9, 2004
  3. news.rcn.com
    Replies:
    2
    Views:
    1,174
    Roedy Green
    Dec 10, 2007
  4. David Filmer
    Replies:
    19
    Views:
    279
    Kevin Collins
    May 21, 2004
  5. Andrew Falanga
    Replies:
    2
    Views:
    215
    Andrew Falanga
    Nov 22, 2008
Loading...

Share This Page