scope question

Vineet vidog112 at YAHOO.COM
Tue Aug 7 16:16:47 EDT 2001


The reason you get an error like that, is because 'count' can only be
read, not changed. In your first example, you are only referencing 'count'
and therefore, no exception.  However, in your second example, you are
attempting to write to a global variable from a local function, which is
not allowed.

I had a similar problem like that. I got around it by putting all my
functions and variables in a class. You can access all variables that are
in a class when you create an instance of the class.

Hope this helps.
vineet

Mark Robinson wrote:

> Can anyone explain the following behaviour to me
>
> if I type:
>
> count = 0
> def function():
>         print count
>
> function()
>
> that works fine, however, if I type this:
>
> count = 0
> def function():
>         count += 1
>         print count
>
> function()
>
> I get the following exception
>
> UnboundLocalError: local variable 'count' referenced before assignment
>
> why does it find the global variable in the first case and not in the
> second?
>
> blobby




More information about the Python-list mailing list