[Tutor] Referencing global variables

S A buc40@bemail.org
Wed, 4 Sep 2002 12:01:48 -0700


> jcosby@mindspring.com buc40@bemail.orgDate: Wed, 04 Sep 2002 11:58:06
> RE: [Tutor] Referencing global variables
>>Reply-To: <jcosby@mindspring.com>
>> "Jon Cosby" <jcosby@mindspring.com> <tutor@python.org> [Tutor] Referencing global variablesDate: Wed, 4 Sep 2002 12:35:56 -0700
>>
>>Why does this not work:
>>
>>>>> count = 0
>>>>> def increment(n):
>>...     for i in range(n):
>>...             count = count + 1
>>...     return count
>>...
>>>>> increment(5)
>>UnboundLocalError: local variable 'count' referenced before assignment
>>
>>"count" is global, isn't it? It would seem I should be able to reference it
>>in the function. I don't want to initialize it each time the function runs,
>>I'm actually trying to count instances in a recursive function.
>>
>>Jon Cosby
>
>
>I think this is not so. Someone else correct me if I'm wrong. But the only value passed to the function is 5. Therefore increment does not know what the value of count is. One correction is as follows:
>
>>>> def increment(n):
>...     count = 0
>...     for i in range(n):
>...             count = count + 1
>...     return count
>... 
>>>> increment(5)
>5
>
>However, this may not be the solution for you. Maybe you want count to be defined outside of the function? You can then try the following:
>>>> count = 0
>>>> def increment(n, count):
>...     for i in range(n):
>...             count = count + 1
>...     return count
>... 
>>>> increment(5, count)
>5
>
>Maybe this is what you are looking for. Anybody else?
>
>Good Luck.
>SA
>
>
>
>"I can do everything on my Mac that I used to do on my PC, plus alot more ..."
>
>-Me



"I can do everything on my Mac that I used to do on my PC, plus alot more ..."

-Me

------------------------------------------------------------
Free, BeOS-friendly email accounts: http://BeMail.org/
BeOS News and Community: http://www.BeGroovy.com/


---------------------------------------------------------------------
Express yourself with a super cool email address from BigMailBox.com.
Hundreds of choices. It's free!
http://www.bigmailbox.com
---------------------------------------------------------------------