views:

122

answers:

3

I have a simple for loop problem, when i run the code below it prints out series of 'blue green' sequences then a series of 'green' sequences. I want the output to be; if row[4] is equal to 1 to print blue else print green.

 for row in rows:
        for i in `row[4]`:
            if i ==`1`:
                print 'blue '
            else:
                print 'green '

Any help would be grateful

thanks

Yas

+3  A: 

Try something like this:

for i in xrange(len(rows)):
  if rows[i] == '1':
    print "blue"
  else:
    print "green"

Or, since you don't actually seem to care about the index, you can of course do it more cleanly:

for r in rows:
  if r == "1":
    print "blue"
  else:
    print "green"
unwind
why not doing `for row in rows` and testing the value of row ?
LB
@LB: Um ... Because I was being a bit literal-minded, I guess. It happens. I'll edit, thanks!
unwind
+2  A: 
if rows[4] == 1:
    print 'blue'
else:
    print 'green'
Morgaelyn
+2  A: 

the enumerate() function will iterate and give you the index as well as the value:

for i, v in enumerate(rows):
    if i == 4:
        print "blue"
    else:
        print "green"

if you want to print blue on every fourth line else green do this:

for i, v in enumerate(rows):
    if i % 4 == 0:
        print "blue"
    else:
        print "green"
fuzzy lollipop