[Tutor] Referencing global variables
Jon Cosby
jcosby@mindspring.com
Wed, 4 Sep 2002 12:35:56 -0700
This is a multi-part message in MIME format.
------=_NextPart_000_0000_01C2540F.9DAD2D10
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
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
jcosby@mindspring.com
www.jcosby.com
------=_NextPart_000_0000_01C2540F.9DAD2D10
Content-Type: text/html;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv=3DContent-Type content=3D"text/html; =
charset=3Diso-8859-1">
<META content=3D"MSHTML 6.00.2719.2200" name=3DGENERATOR></HEAD>
<BODY>
<DIV><FONT face=3DArial size=3D2>Why does this not work:</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT> </DIV>
<DIV><FONT face=3DArial size=3D2>>>> count =3D =
0<BR>>>> def=20
increment(n):<BR>... for i in=20
range(n):<BR>... &nb=
sp; =20
count =3D count + 1<BR>... return=20
count<BR>...<BR>>>> increment(5)<BR>UnboundLocalError: local =
variable=20
'count' referenced before assignment</FONT></DIV>
<DIV><FONT face=3DArial size=3D2></FONT> </DIV>
<DIV><FONT face=3DArial size=3D2>"count" is global, isn't it? It would =
seem I should=20
be able to reference it in the function. I don't want to initialize it =
each time=20
the function runs, I'm actually trying to count instances in a recursive =
function. <BR></FONT></DIV>
<P><FONT size=3D2>Jon Cosby<BR><BR><A=20
href=3D"mailto:jcosby@mindspring.com">jcosby@mindspring.com</A><BR><A=20
href=3D"http://www.jcosby.com">www.jcosby.com</A> </FONT></P>
<DIV> </DIV></BODY></HTML>
------=_NextPart_000_0000_01C2540F.9DAD2D10--