[Tutor] strange variable problem
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Fri May 21 16:32:30 EDT 2004
On Fri, 21 May 2004, Dave S wrote:
> Please excuse my poor codeing ... but I have a problem.
>
> ftseptr is setup as a global variable, value -1,
> yftseptr is setup as a global variable, value 0
Hi Dave,
Ah! Common gotcha: when using global variables in functions, you may need
to declare that the variable is 'global' in nature. For example:
###
count = 0
def makeNextName():
global count
nextName = "name%s" % count
count = count + 1
return nextName
###
If the 'global count' declaration in the function is missing, then we'll
get the same UnboundLocalError that you're receiving in your program, so I
suspect the same thing is happening there.
Another example of this is in the Python Programming FAQ, under the title
"How do you set a global variable in a fucntion?":
http://python.org/doc/faq/programming.html#how-do-you-set-a-global-variable-in-a-function
So people do run into this enough that it's a FAQ entry. I get the
feeling, sometimes, that globals are awkward in Python to discourage their
use. *grin*
Hope this helps!
More information about the Tutor
mailing list