Ad

Variables In Input Questions

- 1 answer

So, I know that if you do:

variable1 = 10

variable2 = variable1

then variable2 will be 10. But if you do:

variable1 = 10

and then ask for an input:

variable2 = input("...")

and type variable1 as the input, then variable2 will be 'variable1' instead of 10. How can I change this so that variable2 equals variable1 after inputting the string variable1?

Ad

Answer

If you're sure that you really want to do this, you can use eval, but this is a bad practice, and leaves you susceptible to arbitrary code injection.

>>> variable1 = 10
>>> variable2 = eval(input())
variable1
>>> variable2
10

A slightly better approach might be to use the globals or locals builtins, but this is still a bad practice.

>>> variable2 = globals()[input()]
variable1
>>> variable2
10
Ad
source: stackoverflow.com
Ad