For/else question about new lines


Hello, when I run the following code why does every item in fruits start on its own line?:

fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']

print 'You have...'
for f in fruits:
    if f == 'tomato':
        print 'A tomato is not a fruit!' # (It actually is.)
    print 'A', f
    print 'A fine selection of fruits!'

If I add a comma after the f in print 'A'f, then everything prints on the same line. I thought the comma should cause each item to go on its own line as opposed to causing it all to be on one line. Can someone please explain this to me? Thanks in advance.


currently the comma is used to concatenate the string ('A) and f variable

to achieve what you want you would need something like:

print 'A %s' % f,

.format() would be better then %s, but format is not part of the course


Thanks so much for the response. Why isn't everything printing out on one line though? What is causing each item to be on its own line?


They are on one line now after you applied my suggested fix? Please show by the means of output what you mean


The default setting for codecademy is to print each item on a separate line, unless it's a string. I don't know if there is anyway to change this.


False, this has absolutely nothing to do with codecademy what so ever. This is just python behavior.


This is the output I get when not putting a comma after the f in print 'A', f on line 8:

You have...
A banana
A apple
A orange
A tomato is not a fruit!

But when I do put a comma there it all prints on one line. I thought it would be the opposite. I thought it would all print on one line UNLESS I put a comma.


no, each print statement prints on a seperate line unless you include a comma

now that is cleared, did you get it to work?


Yes I did. I went back to exercise 12. It will print out on separate lines and the comma is used to put it all on one line. I don't know how I mixed that up. Thanks for all the help!


awesome. thanks for the reply


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.