[Tutor] Tutor Digest, Vol 25, Issue 54

Alan Gauld 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 
> function?

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

def f():
   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:

def g(n):
    n = 27
   return n

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" 

Alan G
Author of the learn to program web tutor

More information about the Tutor mailing list