[Tutor] Question about global variables on modules
Dave Kuhlman
dkuhlman at rexx.com
Mon Apr 7 18:23:08 CEST 2008
On Fri, Apr 04, 2008 at 10:25:30PM -0300, Tiago Katcipis wrote:
> I know its not such a pretty thing to have global variables but its only
> for an exercise my teacher told to do. Its a function to calculate the
> results of a matrix using jacob. I want to inside the module (inside a
> function on the module )assign a value to a global variable, but the
> only way i found to do this inside the own module function is importing
> the module inside himself. Is there another way of doing this? its kind
> odd to import the module to himself, i think :-)
If you want to assign a value to a global variable from within a
function, use the global statement. Examples:
A_GLOBAL_VALUE = 0
# Example: assign value to local variable
def t1():
a_value = 4
return a_value * 3
# Example: assign value to global variable
def t2():
global A_GLOBAL_VALUE
A_GLOBAL_VALUE = 4
return a_value * 3
# Example: get (but do not set) the value of a global variable
def t3():
a_value = A_GLOBAL_VALUE
print a_value
def test():
print t1()
print t2()
print A_GLOBAL_VALUE
print t3()
test()
See http://docs.python.org/ref/global.html.
Note that to *get* (not set) the value of a global variable from
within a function, you do not need to use the global statement.
- Dave
--
Dave Kuhlman
http://www.rexx.com/~dkuhlman
More information about the Tutor
mailing list