-2

I have a list with values 'ab' and 'cd'. I want to make a variable name based on the values of the list like var_ab or var_cd based on the user's input. If the user inputs 1, then make a variable var_ab and if the user inputs 2, then make var_cd.

li = ['ab', 'cd']

How to do it in python ?

2 Answers2

1

While there's no direct way of doing that (that I'm aware of), You can achieve the same results using a dictionary. for example:

vars = {'ab':0,'cd':0}

in order to change or access the value of ab, use vars['ab'] or vars.ab.

If you want to access a variable by a name stored in a variable, then you can only use the first method. For example:

vars = {'ab':0,'cd':0}
var = input('what variable do you want to read? ')
print(vars[var])

Edit: if you absolutely need a custom variable name, you can use exec(), as suggested by @Teejay Bruno. but note that it would require you to use exec() in every mention of the variable. and most importantly it's never a good idea to let the user affect code in any way. for example, the following code:

var = input('enter a variable to create')
exec(var + '=0')

would create a variable with a custom name and value 0. but it could be exploited in many ways by inputing text that would crash or make changes to the code. for instance, inputing forbidden characters for variable names (like '?') would crash the program

atanay
  • 174
  • 10
0

you can add a new variable by locals()[var_name] = var_value

Bogdan Prădatu
  • 325
  • 5
  • 15