- Code: Select all
for i in range(0,2):
a = 2
How would I go about adding the number i after 'a' in the loop so that after running this loop two variables are set to 2, a1 and a2?
I'm using Python 2.7
for i in range(0,2):
a = 2
for i in [1,2] :
setattr(__builtins__,"a"+str(i),2)
>>> for i in [1,2] :
... setattr(__builtins__,"a"+str(i),2)
...
>>> a1
2
>>> a2
2
>>> a3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a3' is not defined
>>> for i in range(2):
... globals()["a{}".format(i+1)] = 2
...
>>> a1
2
>>> a2
2
>>>
>>> for i in range(2):
... exec("a{} = 2".format(i+1))
...
>>> a1
2
>>> a2
2
>>>
ochichinyezaboombwa wrote:This thread is NC-77.
Users browsing this forum: No registered users and 4 guests