How to print variable name by input
, Example:
a = 1
b = 2
what_variable = input('Which Variable?: ') #User for example introduces 'b'
Console: 2
How to print variable name by input
, Example:
a = 1
b = 2
what_variable = input('Which Variable?: ') #User for example introduces 'b'
Console: 2
You can write
print(globals()[what_variable])
but it's not a good approach. Use a dict instead
You can use exec
:
var = input('Which Variable?: ')
exec("print(" + var + ")")
Output:
Which Variable?: b 2 >>
Just do the following:
print(eval(input('Which Variable?: ')))
You can also do
print(globals()[input('Which Variable?: ')])
While the other answers seem to address the obvious solution, it's not very 'Pythonic'. The main issues with these is, by far, safety. Let's say that your user inputs apiKey
, and you happen to have a variable by that name... let's just say your bank statement is probably looking at a slight increase in magnitude. What most people in these answers don't realise is that using .globals()[input()]
is no safer than eval(input())
, because, shockingly, people store private info in variables. Alternatively, if it points to a method, e.g
a = print
b = os.system
eval(input())()
I could enter any function name there, and the damage would be done before the second ()
executes.
Why? Well, let's take a look at how exec
and eval
work (I won't go into the difference here, see this question for that). All they do is evaluate the string as Python code, and (simplifying here) return the value of the evaluation:
var1 = 3
print(eval("var1"))
# ====is equal to====
var1 = 3
print(var1)
(where var1
as a string obviously comes from the input typed in)
But if someone enters something malicious, this is essentially the basis of an SQL injection:
(where userInput
is substituted by a user's input into an input()
)
userInput = "a + os.system('reboot now')"
print(eval(userInput))
# ====is equal to====
print(a + os.system('shutdown now')
and you suddenly find your computer's off.
Therefore, we'd either use a:
x={a:1, b:2}
, then do x[input()]
x=[1, 2]
, then do x[["a", "b"].index(input())]
if/else
set? It's not good practise, because of the safety concerns outlined above. What most people seem to miss about dictionaries (or my array option) is that if you enter a malformed input (i.e not a
or b
), it would result in either uncaught errors being thrown, or undefined
s being thrown around. And if you're going to do input validation, you're using an if
statement anyway, so why not do it from the onset?