3

I am using python and would like to know if it would be possible to ask the user for the name of a variable and then create a variable with this name. For example:

my_name = input("Enter a variable name") #for example the user could input orange
#code to set the value of my_name as a variable, say set it to the integer 5
print(orange) #should print 5 if the user entered orange

I know it can be done using a dictionary but I would like to know whether this is possible without creating an additional object. I am using python 3. Thanks.

Kevin
  • 74,910
  • 12
  • 133
  • 166
Hadi Khan
  • 577
  • 2
  • 8
  • 30

2 Answers2

6

You can use the dictionary returned by a call to globals():

input_name = raw_input("Enter variable name:") # User enters "orange"
globals()[input_name] = 4
print(orange)

If you don't want it defined as a global variable, you can use locals():

input_name = raw_input("Enter variable name:") # User enters "orange"
locals()[input_name] = 4
print(orange)
EvenLisle
  • 4,672
  • 3
  • 24
  • 47
0

If your code is outside a function, you can do it by modifying locals.

my_name = raw_input("Enter a variable name")  # Plain input() in Python 3
localVars = local()
localVars[my_name] = 5

If you're inside a function, it can't be done. Python performs various optimizations within functions that rely on it knowing the names of variables in advance - you can't dynamically create variables in a function.

More information here: https://stackoverflow.com/a/8028772/901641

Community
  • 1
  • 1
ArtOfWarfare
  • 20,617
  • 19
  • 137
  • 193
  • This answer works outside a function. You said that it is not possible to do it inside a function but the answer by @EvenLisle works inside a function as well. Could you please explain why this happens? – Hadi Khan Apr 23 '15 at 13:11
  • @AbdulHadiKhan: You're modifying globals in his case. Python takes a lot longer to access global variables than local variables. – ArtOfWarfare Apr 23 '15 at 13:13