-1

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)
CrotaL
  • 19
  • 5
  • 1
    You could make `val` a dictionary or list with a string inside it and modify the list/dict in your function, but what's wrong with using `global` here? – Jared Smith May 12 '23 at 11:49
  • 1
    It is not clear what is supposed to be the expected output. Also, `val` is an argument of the function and a variable name in the function. It is confusing. Please describe better what you want to accomplish. Add expected inputs/outputs/behavior – alec_djinn May 12 '23 at 11:50
  • 1
    Read https://nedbatchelder.com/text/names.html. A function *cannot* affect the variable that provides the *value* that gets bound to its parameter. As far as the definition of `setval` is concerned, there is *no* difference between `val = 'test'; setval(val)` and `setval('test')`. – chepner May 12 '23 at 11:56

2 Answers2

0

"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)

0

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.

alec_djinn
  • 10,104
  • 8
  • 46
  • 71