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.
Yes, you can increment and assign to some other variable and can return the incremented value.
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.
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.
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)
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', ' ']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With