[Tutor] Tutor Digest, Vol 25, Issue 54
alan.gauld at freenet.co.uk
Wed Mar 22 17:04:36 CET 2006
> Anyway, how can i declare a global variable and assign a value to it in a
Variables in Python are only global in the sense of a file. You cannot
declare a global that spans multiple files. However you can import
a variable reference from one file to another. This is "A Good Thing(TM)"
since it avoids most of the evils of global variables.
You can assign to a global variable from within a function by telling
the function to use the global name:
x = 42
global x # say use the external variable called x
x = 27
f() # actually assigns the value
But that's bad practice in most cases and its better to pass
the variable in as an argument and return the new value:
n = 27
x = g(x) # same effect as calling f() above
You can read more anbout this in my tutorial
topic "What's in a Name?" (And more about
functions and modules in the "Modules & Functions"
Author of the learn to program web tutor
More information about the Tutor