0

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

6
  • that doesn't seem like a valid python code. also, what is rows? Commented Mar 11, 2010 at 16:31
  • do you mean the contents of row at index 4 ( the fifth element ) is == 1 print blue else print green, or do you want to print blue on every forth line else print green? Commented Mar 11, 2010 at 16:33
  • Is rows 1 or 2 dimensional list? Commented Mar 11, 2010 at 16:33
  • Homework? If so, please label it as [homework]. Commented Mar 11, 2010 at 16:58
  • 1
    I don't think you're using the backticks correctly (do you really want the repr of row[4]?). Is that a literal cut and paste of your code or did you edit it? Commented Mar 11, 2010 at 17:00

3 Answers 3

3

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"
Sign up to request clarification or add additional context in comments.

2 Comments

why not doing for row in rows and testing the value of row ?
@LB: Um ... Because I was being a bit literal-minded, I guess. It happens. I'll edit, thanks!
2

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"

Comments

1
if rows[4] == 1:
    print 'blue'
else:
    print 'green'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.