Assigning to global variables from within a function

Irmen de Jong irmen at -NOSPAM-REMOVETHIS-xs4all.nl
Sat Jul 12 22:42:06 CEST 2003


Psymaster wrote:

> I want to do this:
> 
> int= 0
> 
> def change_int():
>     	int += 1
> 
> change_int()
> 
> but of course it doesn't work, Python thinks it is a local 
> variable and refuses to reference the global one. So what would 
> be a good way of doing this. Note that creating a new global 
> variable from within the function isn't convenient because the 
> function is intended to be used in loops.

A function that modifies a global is generally considered bad
design (it has 'side-effects').

But if you really need to do this, just add a 'global' statement:

def change_i():
     global i
     i+=1


PS don't use 'int' for a name of your own, it is a builtin in Python.





More information about the Python-list mailing list