Why 'for/else' question


#1



https://www.codecademy.com/en/courses/python-beginner-en-cxMGf/2/4?curriculum_id=4f89dab3d788890003000096

Just a question: Why does it executes the print 'A', f first, in stead of first going through all the list and comparing if A is a tomato (A==tomato)?

In way I expected this to happen:


You have...
A tomato is not a fruit!
And the break would prevent the following to print:

A banana
A apple
A orange
None


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.)
        break
    print 'A', f
else:
    print 'A fine selection of fruits!'


#2

I just ran your code and it outputs:

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

The reason why it isn't outputting the way you want it to is because it is going through each item of the list IN ORDER. So at first, your f is "banana" (first item of your list). "banana" != "tomato" and so it skips that condition because it's FALSE. It will keep going through the list until is reaches "tomato" in the list and the loop breaks and so "pear" and "grape" are also never evaluated.

Therefore, what you are outputting right now is correct.


#3

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