[Tutor] Referencing global variables
Sean 'Shaleh' Perry
shalehperry@attbi.com
Wed, 4 Sep 2002 12:41:06 -0700
On Wednesday 04 September 2002 12:35, Jon Cosby wrote:
> Why does this not work:
> >>> count =3D 0
> >>> def increment(n):
>
> ... for i in range(n):
> ... count =3D 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 referenc=
e it
> in the function. I don't want to initialize it each time the function r=
uns,
> I'm actually trying to count instances in a recursive function.
>
if you want to *change* a global you need to declare it global.
def increment(n):
global count
for i in range(n):
count =3D count + 1 # or count +=3D 1
return count