-1

I come from PHP background, and I am trying to print each iteration. I can not understand how to do it in Python

>>> a0, a1, a2 = [12, 5, 8]
>>> b0, b1, b2 = [5, 9, 11]
>>> categories = [0, 1, 2]
>>> for i in categories:
        print(a+i)

Error:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: name 'a' is not defined
>>> for i in categories:
...    print('a'+i)
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> for i in categories:
...     print(a+str(i))
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: name 'a' is not defined

I know it is basic, but I do not know how to solve it.

Edit:

>>> print a0
12
>>> print a2
8

a0, a1, a2 is variable. Since I have 0,1,2 in for I don't need to write a0, a1, a2, b0, b1, b2 manually.

Nimatullah Razmjo
  • 1,831
  • 4
  • 22
  • 39

2 Answers2

1

I don't think you would do it this way in python. More pythonic would be to store the values as a list or an array like:

a = [1, 2, 3]
cat = [0, 1, 2]
for i in cat:
    print(a[i])
joed4no
  • 1,243
  • 13
  • 17
-4
>>> a0, a1, a2 = [12, 5, 8]
>>> b0, b1, b2 = [5, 9, 11]
>>> categories = [0, 1, 2]

for i in categories:        
    print(eval('a'+str(i)))

eval will make the string into a variable, so will printing variable a0,a1,a2

output :
12
5
8
P. Ray
  • 1
  • 4
  • Welcome to Stack Overflow! While you may have solved this user's problem, code-only answers are not very helpful to users who come to this question in the future. Please edit your answer to explain why your code solves the original problem. – Joe C Jan 29 '17 at 08:18
  • @Joe C, i have edit my answer, sorry about this. – P. Ray Jan 29 '17 at 08:24