variable scope?

Hartmann Schaffer hs at paradise.nirvananet
Mon Dec 25 19:19:19 EST 2000


In article <c5S16.8616$KY1.23318 at news1.rivrw1.nsw.optushome.com.au>,
deadmeat <root@[127.0.0.1]> wrote:
>This doesn't work:

it's all in the manual

>---
>import time, string
>
>month = "2"
>year = "2000"
>
>def foo():

    global year
    # unless you insert this declaration, an assignment to year introduces
    # a new variable named "year" in function "foo".  when you try to read
    # it after having skipped the assignment you'll get the message below

>   if string.atoi(month) <= 3:
>      year = `string.atoi(year) - 1`
>      print year

    # i suspect in your actual code the print statement wasn't indentes
    # as shown hear

>
>foo()
>---
>
>reporting:
>
>Traceback (most recent call last):
>  File "pfft.py", line 11, in ?
>    foo()
>  File "pfft.py", line 8, in foo
>    year = `string.atoi(year) - 1`
>UnboundLocalError: Local variable 'year' referenced before assignment
>
>but this does
>
>---
>import time, string
>
>month = "2"
>year = "2000"
>
>def foo():
>   year = "2000"
>   if string.atoi(month) <= 3:
>      year = `string.atoi(year) - 1`
>      print year
>
>foo()
>---
>
>how do I force foo() to use the global 'year' variable?

hs



More information about the Python-list mailing list