modifing function's parameters global value

Michele Simionato mis6 at pitt.edu
Tue May 13 14:05:15 EDT 2003


"Federico" <maschio_77 at hotmail.com> wrote in message news:<b9qqeo$qbq$1 at lacerta.tiscalinet.it>...
> How can I modify the global value of function's parameters
> Thanks

I guess you want to have side effects in your function, changing
a global variable. You can do that with the 'global' keyword:

def f( ):
    global x
    x+=2

#example:
x=1
f( )
print x # =>3

Notice that you cannot do

def f(x):
    global x
    x+=2

(SyntaxError: name 'x' is local and global).

Another possibility is to pass a mutable object,
i.e. a list:

def g(ls):
    ls[0]+=2
    
ls=[1]
g(ls)
print ls[0] # =>3

Anyway, you should post your use case in order to have a more helpful
answer. Typically a function with side effects is not a good idea and
there could be better solutions.


                                                  Michele




More information about the Python-list mailing list