-2

How to print variable typed by user, for example user types

var = input("Type variable name: ")

and program finds that var. and prints it

Sorry if this question already exists but i didn't find it. (Also sorry for my bad english)

Sheri
  • 1,383
  • 3
  • 10
  • 26
def750
  • 19
  • 5
  • 2
    You should create some sort of mapping between *strings* and the *objects* you are interested in. The use should have no knowledge of any *variables*. Just use a `dict` – juanpa.arrivillaga Nov 07 '19 at 20:03
  • 1
    Simply: print(var) – Sheri Nov 07 '19 at 20:06
  • To echo @Sheri, once it's saved as a variable, all variables can be printed the same way in python, with `print()`. One nitpick with the posted code: `input()` already returns a string by default, so there's no need to cast it to a string with `str(input())`. If there's some other scenario you need, please provide a [mcve] for better answers – G. Anderson Nov 07 '19 at 20:16
  • 1
    Does this answer your question? [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – squadrick Nov 07 '19 at 20:22
  • @G.Anderson yes you are right i have edited and removed str() – Sheri Nov 07 '19 at 20:22

1 Answers1

0
variableName = input("Type var name: ")

try:
  print(globals()[variableName])
except:
  print("Variable not found")
Sheri
  • 1,383
  • 3
  • 10
  • 26
squadrick
  • 770
  • 3
  • 21