0

How could I select a variable with an input and than change its value, this is the best that I could come up with but it doesn't seem to work.

itm1 = 1
itm2 = 1
x = raw_input()
x += 1
print (itm1)

I'm trying to get it so that anyone of the variables could be changed depending on the input.

1
  • 2
    How about defining a dictionary with itm1, itm2 as keys. You can get itm1 as input and change the values Commented Jun 8, 2017 at 5:01

3 Answers 3

2

It's possible, but you really shouldn't do that in most cases. Nicer way is to store the parameters in a dictionary and do something like:

d = {
  'itm1': 1,
  'itm2': 1,
}
x = raw_input()
d[x] += 1
print (d['itm1'])

If you really need to change the local variables and have a good reason not to rewrite it to a proper collection, you can use this: (but it's fugly)

locals()[x] += 1
Sign up to request clarification or add additional context in comments.

Comments

1

What do you want to do exactly?

If you want to add the input value to an existing variable you can just do this:

itm1 = 1
itm2 = 1
x = raw_input()
itm1 += x
print (itm1)

Your question is unclear regarding the aim. If you want to select one variable to change depending on the input, you can try this:

itm = [1, 1]
x = raw_input()
itm[x] += 1
print(itm[x])

Of course this assumes you're entering a value in the bounds of the aray indices.

Or you can define a dictionary

y = {"itm1": 1, "itm2": 1}
x = raw_input()
y[x] += 1
print( y[x] )

Comments

-1

You could use 'exec'. This takes variable name through raw_input and executes "variable += 1"

itm1 = 1
itm2 = 1
exec(raw_input()+'+=1')
print(itm1)

But this isn't the best method. Use dictionaries or lists instead

2 Comments

Downvoted for "should". No - they definitely shouldn't use exec unless that's the absolute last resort. :(
sry, typo, it was supposed to be "could"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.