I want the value of val to be changed to new instead of test. Is there a way to achieve this without using a global in define?
val = 'test'
def setval(val):
val = 'new'
return val
setval(val)
print(val)
I want the value of val to be changed to new instead of test. Is there a way to achieve this without using a global in define?
val = 'test'
def setval(val):
val = 'new'
return val
setval(val)
print(val)
"val" inside the function setval is scoped and only changes/assigns to the argument val for the function setval.
if you want to change the variable val then you should do val = setval(val)
You question is not fully clear to me, but I think you want to do something like this:
def setval(var_name, new_value):
globals()[var_name] = new_value
val = 'something'
print(val)
setval('val', 'something else') #note 'val' is a string here!!
print(val)
It will print:
something
something else
You use the globals() function to access the variable and set it to another value.