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.

0

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, It works. However do I always have to do it with globals()?
I'm not aware of any simpler way to achieve what you ask than via globals() or locals().
locals isn't guaranteed to work.
If the assignment and use are in the same lexical scope, then yes, it is.
How do you access this variable later in the code without knowing the user input beforehand?
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

2 Comments

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?
@AbdulHadiKhan: You're modifying globals in his case. Python takes a lot longer to access global variables than local variables.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.