Joe
Joe

Reputation: 13

TypeError:'int' object is not iterable when I try to iterate through my inner loop?

I am not sure what the problem is with my loop structure. Maybe it's a naming problem since the count variable and SubElement names use the same variable. Any help is appreciated.

from xml.etree import ElementTree as ET

root = ET.Element("painter")
root.set('version', '1.0')
linenum = 0
pointnum = 0

smpl_data = [[[20,40],(0,0,1,1)],[[10,50],(0,0,1,1)],[[78,89],(0,0,1,1)]]

while linenum <= len(smpl_data): #smpl_data change to self.lines
    elem_line = ET.SubElement(root,"line" + str(linenum), attrib={"r": "1", "g": "2", "b": "3", "a": "4"})                     
    elem_line.set("r", smpl_data[linenum][1][0])
    print elem_line.attrib.get("r")                      
    elem_line.set("g", smpl_data[linenum][1][1])
    print elem_line.attrib.get("g")
    elem_line.set("b", smpl_data[linenum][1][2])
    print elem_line.attrib.get("b")
    print elem_line.get("a")
    elem_line.set("a", smpl_data[linenum][1][3])
    print elem_line.attrib.get("a")

    for pointnum in linenum:
        elem_point = ET.SubElement("line" + str(linenum), "point" + str(pointnum), attrib={x: "10", y: "20"})
        print elem_point
        print elem_point.get("x")
        elem_point.set("x", smpl_data[linenum][0][0])
        print elem_point.attrib.get("x")
        print elem_point.get("y")
        elem_point.set("y", smpl_data[linenum][0][1])
        print elem_point.attrib.get("y")
        pointnum = pointnum + 1
   linenum = linenum + 1

I get the error right when it tries to begin iterating through the inner loop, for pointnum in linenum. Not sure why?

I apologize for not being more clear.

This is the full error:

  Traceback (most recent call last):
  File "C:\Users\joel\Desktop\open-autism-software\software\asd\pen\writexml.py", line 57, in <module>
  for pointnum in linenum:
  TypeError: 'int' object is not iterable

My goal in the full program is to be able to add all the specific (x,y) points as attributes to their respective SubElement (line). Each line is attached to the main root. However, the number of (x,y) points is variable with my persistent data because each line can be a different length.

The XML doc should look something like this:

<root>
<line r="0", g="0", b="1", a="1">
    <point x="20" y="30">
    <point x="10" y="15">
    <point x="15" y="25">
    ...
</line>
<line r="0", g"1", b="1", a="1">
    ...
</line>
...
</root>

Upvotes: 0

Views: 2303

Answers (2)

Michael Lorton
Michael Lorton

Reputation: 44386

You probably want

for pointnum in range(linenum):

That is, all the numbers from zero to one less than linenum

Upvotes: 3

Steve Prentice
Steve Prentice

Reputation: 23514

linenum is not iterable. It's hard to tell what you are trying to do here, but perhaps for pointnum in smpl_data[linenum]: would be what you want?

Upvotes: 1

Related Questions