-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
Nouman
  • 6,947
  • 7
  • 32
  • 60
asdasd
  • 33
  • 2

4 Answers4

2

You can write

print(globals()[what_variable])

but it's not a good approach. Use a dict instead

blue_note
  • 27,712
  • 9
  • 72
  • 90
0

You can use exec:

var = input('Which Variable?: ')

exec("print(" + var + ")")

Output:

Which Variable?: b
2
>> 
Nouman
  • 6,947
  • 7
  • 32
  • 60
0

Just do the following:

print(eval(input('Which Variable?: ')))

You can also do

print(globals()[input('Which Variable?: ')])
Sam Chats
  • 2,271
  • 1
  • 12
  • 34
  • Would not invoking `eval` also permit arbitrary code execution? – ifly6 Aug 09 '19 at 17:44
  • 1
    Avoid using `eval`. If you had this running on a server, I could enter in some of my own nasty python code: `import os; os.system('')` – SyntaxVoid Aug 09 '19 at 17:48
  • Yes, `eval`'s bad; but how does it differ from `exec`? – Sam Chats Aug 09 '19 at 17:52
  • 1
    @SamChats, `eval` is only able to evaluate expressions which makes it *somewhat* safer than `exec`. `exec` allows you to execute any arbitrary python code. In my comment above, you actually can't put the `import os` part in the eval statement since it will raise a syntax error. However if `os` was already imported, then you could still run anything with `os.system(...)`. – SyntaxVoid Aug 09 '19 at 18:22
0

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:

  • Dictionary (or object): x={a:1, b:2}, then do x[input()]
  • Array x=[1, 2], then do x[["a", "b"].index(input())]
  • Simply don't. Find a way to work around it. What's wrong with an 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 undefineds 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?
Geza Kerecsenyi
  • 1,127
  • 10
  • 27