0

I'm setting up a python based data program, and want to solve this 'for-loop' and 'variable assignment' problem.

I'm using python 3.7.2 and jupyter notebook


for i in range(10):
    a = 1
    a_i = 2


print(a)
print(a_i)
print(a_1)




1
2
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-14-ffb07f4b1734> in <module>
      6 print(a)
      7 print(a_i)
----> 8 print(a_1)

NameError: name 'a_1' is not defined

I expect a_1 should be 2 because it is assigned in the for loop. I mean a_1 ~ a_9 all should be 2, but a_i is 2. I don't understand why a_1 ~ a_9 is is not defined.

0

1 Answer 1

1

because that's not how variables work.

the variable a_i is a uniquely named scalar variable called "a underscore i". The i has no relationship whatsoever with the other completetly unrelated scalar variable called "i". If there was, what would happen if you used a variable like "item_id" in your loop, would you expect that to expand to "1tem_1d" and "2tem_2d"?

Try

a = []

for i in range (0,5):
   a.append( i * 2 )

print (a[1])
print (a[2])

you could also use a dictionary.

a = {}

for i in range (0,5):
   a[i] = i * 2

print (a[1])
print (a[2])

Sign up to request clarification or add additional context in comments.

1 Comment

I figure it out that it is because of parsing matter. computer understand 'a_i' itself as a symbol, so 'a_1', ... 'a_2' can not be assigned.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.