Skip to content Skip to sidebar Skip to footer

Setting User Input To Variable Name

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(

Solution 1:

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

input_name = raw_input("Enter variable name:") # User enters "orange"globals()[input_name] = 4print(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] = 4print(orange)

Solution 2:

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

Post a Comment for "Setting User Input To Variable Name"