0

How could i get below code working? I want to assign value to variable Reputation Risk_22may_only. I got the below code from here. But it doesn't work for me

risk_type="Reputation Risk"

 xxx1=risk_type + "_22may_only"
exec(xxx1 + " = 'something else'")

exec(xxx1 + " = 'something else'")

Traceback (most recent call last):

  File "C:\IPython\core\interactiveshell.py", line 2862, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)

  File "<ipython-input-38-c9a2a2cf48c3>", line 1, in <module>
    exec(xxx1 + " = 'something else'")

  File "<string>", line 1
    Reputation Risk_22may_only = 'something else'
                                  ^
SyntaxError: invalid syntax
Ni_Tempe
  • 307
  • 1
  • 6
  • 20
  • 4
    There's a space in your variable's name, making it invalid. – Aran-Fey May 23 '18 at 15:36
  • 2
    On a side note, this is not a good way of doing this. I would recommend that if you need to create "variables" dynamically, consider using a dictionary instead. – Robert Talada May 23 '18 at 15:40
  • 2
    As most of the answers say in the linked question, this is _not_ a good idea. Also see [Why you don't want to dynamically create variables](http://stupidpythonideas.blogspot.com.au/2013/05/why-you-dont-want-to-dynamically-create.html), and the linked article "Keep data out of your variable names". – PM 2Ring May 23 '18 at 15:40
  • @PM2Ring is right and provided a very good link. I will note that there are exceptions. Dynamically creating variables can be advantageous if you write a debugger or an interpreter. I have done it only once, when I made an in-game scripting language for a home-grown game engine. – Robert Talada May 23 '18 at 15:56

0 Answers0