0

I don't understand what's wrong with in this code.

Please let me know how I write to solve this problem.

I'd thought that this might had been good, but it caused the error.

>>> def L():
...     for i in range(3):
...             locals()["str" + str(i)] = 1
...     print str0
... 
>>> L()

If I execute it, the following error happened.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in a
NameError: global name 'str0' is not defined

However, if I use globals(), the error didn't happen(like the following)

>>> def G():
...     for i in range(3):
...             globals()["str" + str(i)] = 1
...     print str0
... 
>>> G()
1

But!!! If I don't use for statement, I can write like this and works well.

>>> def LL():
...     locals()["str" + str(0)] = 1
...     print str0
... 
>>> LL()
1

I want to get the result by using variables set in the method after the above code was executed.

>>> str0
1
>>> str1
1
>>> str2
1
harukaeru
  • 683
  • 6
  • 15
  • 3
    Are you just goofing around with this, or are you actually going to use it for something? If you are going to use the code for something, this is a bad idea. You should instead use a list, or a dictionary with 0, 1, 2 as the keys. – BrenBarn Jan 04 '14 at 21:27
  • Of course I know it's useful to use a list or a dictionary. But I wondered why this error happened. – harukaeru Jan 04 '14 at 21:31
  • Don't do this! You don't have to play around with locals, it is so much simpler to write str[0]=1, str[1]=1, etc. (use lists or dicts, as BrenBarn said). It is always a bad practice to transfer variables into variable names and vice versa. However, this issue is still a good lesson to understand how locals work :). – leeladam Jan 04 '14 at 21:32
  • Thank you! so I understand I should use lists or dictionaries. – harukaeru Jan 04 '14 at 21:41
  • possible duplicate of [Dynamically set local variable in Python](http://stackoverflow.com/questions/8028708/dynamically-set-local-variable-in-python) – jtbandes Jan 04 '14 at 21:59

1 Answers1

3

From the documentation of locals()

Note:

The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

Community
  • 1
  • 1
kazagistar
  • 1,537
  • 8
  • 20