-1

I want to change a variable using another variable without doing the boring old way of:

if choice == 'tuna':
  tuna_num -= 1

Instead I wanted to do it in a just as quick way as the method seen below:

tuna_num = 1
bacon_num = 1

#important bits v
choice = input('Choose a variable name to edit')
(choice)_num -= 1
print((choice)_num)

(Sorry if this is simple or if I'm just being stupid)

loltrox
  • 11
  • 3

2 Answers2

1

Use a dict:

nums = {
    'tuna': 1,
    'bacon': 1,
}

choice = input('Choose a variable name to edit')
nums[choice] -= 1
print(nums[choice])
Samwise
  • 68,105
  • 3
  • 30
  • 44
0

It's a bad thing to do, but:

>>> a = 1
>>> vars()['a'] = 2
>>> print(a)
2

So:

tuna_num = 1
bacon_num = 1

#important bits v
choice = input('Choose a variable name to edit')
if f"{choice}_num" in vars():
    vars()[f"{choice}_num"] -= 1
print(vars()[f"{choice}_num"])
Yevgeniy Kosmak
  • 3,561
  • 2
  • 10
  • 26
  • 1
    Note that this won't work properly in a function; it works fine in global scope, because `vars()` ends up returning the real `dict` globals are stored in, but in a function, it acts like `locals()`, which returns a *copy* of the locals as a `dict`, and mutations to it won't work properly (docs specifically warn against it even in the cases where it works). – ShadowRanger Dec 29 '21 at 02:28