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

霸气de小男生 提交于 2021-02-16 12:40:10

问题


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.


回答1:


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)



回答2:


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', ' ']



回答3:


Your function needs to return the new value. The target variable only has scope within the appendFlag function.

def appendFlag(target, value):
   ...
   return target

m = appendFlag(m, "ok")



回答4:


To have the value of m updated, you should return the concatenated value and assign it to the variable m:

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

print(appendFlag)
m = "hey"
m = appendFlag(m,"ok")
print(m)

OUTPUT:

<function appendFlag at 0x000001423C99F268>
heyok 



回答5:


the variables inside the function has got only function scope, if you change the value of the variable from inside the function it wont get reflected outside the function. if you want to change the value of the global variable m, update it from outside the function as follows

 `def a(target, value):
        target += value
        target += " "
        return target
  m=''
  m=a(m,'ok')

`



来源:https://stackoverflow.com/questions/55275110/python-how-to-change-the-value-of-functions-input-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!