For a toy problem, just use input()
. This is the equivalent of eval(raw_input())
. Don't do this if there is even the possibility that you do not trust input. Whoever has control of the input can execute arbitrary code in your program. So it's a major security vulnerability.
For a more secure approach, put all the values you want to be accessible in a dictionary, and then key that dictionary by your input. The reason to do it this way is that user can only select from the predefined keys you have given them.
eg.
values = {'a': 1, 'b': 2}
key = raw_input()
result = values[key]
print(result)
A halfway house might be to use globals()
or locals()
. globals()
returns your module's global dictionary and locals()
collects all the local variables into a dictionary for you. This will allow the user to select any name from either of those sets of names. So they might be able to select values you want to keep secret.
eg.
password = 'foo'
a = 1
b = 2
key = raw_input() # password would be a valid input here
result = vars()[key]
print(result) # so here we would leak the value of password
As a side note, you are using Python 2. Python 2 is long past its end of life and no longer receives security updates. All new projects should ideally use one of the more recent versions of Python 3 (eg. 3.10). Python 3 only has input()
, but its behaviour is that of raw_input()
in Python 2.