0

I have a function with different arguments. I want to change the value of an argument that has the same name as another argument. Is such a thing possible?

def change(var1, var2, var3, name):
    for i in range(5):
        #change var with the name 'name'
    print(#var with name 'name')

var1, var2, var3 = 0, 0, 0
change(var1, var2, var3, 'var1')

What I have done so far is this:

def change(var1, var2, var3, name)
    for i in range(5):
        if name == 'var1':
            var1 += 1
        elif name == 'var2':
            var2 += 1
        elif name == 'var3':
            var3 += 1
    if name == 'var1':
        print(var1)
    elif name == 'var2':
        print(var2)
    elif name == 'var3':
        print(var3)

var1, var2, var3 = 0, 0, 0
change(var1, var2, var3, 'var1')

But this way of writing it is very inefficient and not suitable if you have a large number of arguments.

dajorah
  • 1
  • 1
  • 5
    You're aware that the value will only be changed within the function, right? The value in the caller will not be affected. – John Gordon May 30 '22 at 20:32
  • 4
    Anytime you have variable with names like `var1`, `var2`, you should probably be using a list or dictionary. – Mark May 30 '22 at 20:34
  • What are you trying to accomplish by doing this? Beware the [XY problem](https://meta.stackexchange.com/q/66377/343832); give the context. Without context, I could say you can accomplish the same thing with simply `print(var1 + 5)`, but I'm sure that's not what you want. This might be a duplicate of [How do I create variable variables?](/q/1373164/4518341) – wjandrea May 30 '22 at 22:32

1 Answers1

0

Consider using a dictionary instead. For example,

def change(values, name):
    for i in range(5):
        #change values[name]
    print(values[name])

values = {
    'var1': 0,
    'var2': 0,
    'var3': 0,
}
change(values, 'var1')
Arj
  • 81
  • 10