Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: how to change the value of function's input parameter?

I tried to modify the value of a string inside a function, like below:

>>> def appendFlag(target, value):
...     target += value
...     target += " "
...
>>> appendFlag
<function appendFlag at 0x102933398>
>>> appendFlag(m,"ok")
>>> m
''

Well, seems the "target" is only changed within the function, but how to make the new value viable outside the function? Thanks.

like image 926
Hind Forsum Avatar asked Mar 21 '19 06:03

Hind Forsum


People also ask

Can you change the value of a parameter in a function?

Yes, you can increment and assign to some other variable and can return the incremented value.

How do you change the value of a variable in a function Python?

Use of “global†keyword to modify global variable inside a function. If your function has a local variable with same name as global variable and you want to modify the global variable inside function then use 'global' keyword before the variable name at start of function i.e.

Can variables be changed Python?

Mutable and immutable typesSome values in python can be modified, and some cannot. This does not ever mean that we can't change the value of a variable – but if a variable contains a value of an immutable type, we can only assign it a new value. We cannot alter the existing value in any way.


2 Answers

This is handled in python by returning.

def appendFlag(target, value):
   target += value
   target += " "
   return target

you can use it like this:

m = appendFlag(m,"ok")

you can even return several variables like this:

def f(a,b):
   a += 1
   b += 1
   return a,b

and use it like this:

a,b = f(4,5)
like image 195
Christian Sloper Avatar answered Oct 22 '22 21:10

Christian Sloper


You need to use an object that can be modified

>>> m = []
>>> def appendFlag(target, value):
...     target.append(value)
...     target.append(" ")
...
>>> appendFlag(m, "ok")
>>> m
['ok', ' ']
like image 32
Kylejie Avatar answered Oct 22 '22 22:10

Kylejie