I need to create 20 variables in Python. That variables are all needed, they should initially be empty strings and the empty strings will later be replaced with other strings. I cann not create the variables as needed when they are needed because I also have some if/else statements that need to check whether the variables are still empty or already equal to other strings.
Instead of writing
variable_a = ''
variable_b = ''
....
I thought at something like
list = ['a', 'b']
for item in list:
exec("'variable_'+item+' = '''")
This code does not lead to an error, but still is does not do what I would expect - the variables are not created with the names "variable_1" and so on.
Where is my mistake?
Thanks, Woodpicker
There are possibly three mistakes. The first is that
'variable_' + 'a'
obviously isn't equal to'variable_1'
. The second is the quoting in the argument toexec
. Doto get
variable_a
etc.The third mistake is that you're not using a
list
ordict
for this. Just dothen get the contents of "variable"
a
withvariable['a']
. Don't fight the language. Use it.I have the same question as others (of not using a list or hash), but if you need , you can try this:
Im assuming you would just need this in the local scope. Refer to the manual for more information on locals
never used it, but something like this may work: