-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,318
  • 1
  • 14
  • 33
  • 1
    This question has been asked many times on Stack Overflow. Here is one such question: http://stackoverflow.com/questions/19122345/to-convert-string-to-variable-name – Ray Toal Jan 29 '17 at 06:41
  • Your stack trace says it all. `NameError: name 'a' is not defined` means you tried to access variable `a` which was not defined. `TypeError: cannot concatenate 'str' and 'int' objects` means you tried to perform `+` operation on `str` & `int` values (both should be same) – Anonymous Jan 29 '17 at 06:42
  • As the error suggests, `name 'a' is not defined` – Ahsanul Haque Jan 29 '17 at 06:42
  • 1
    It's a 4th order duplicate... – DYZ Jan 29 '17 at 06:43
  • >>> for a, i in zip((a0, a1, a2), categories) – Nikhil Rupanawar Jan 29 '17 at 07:21

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,124
  • 10
  • 16
-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