Loop Else vs Regular Else


So after I was done with this exercise, I was trying to digest it and understand what was going on in the code.

Else in loops seem to run only if whatever above follows through completely. So when code reached tomato, it stopped the loop and did not go to the else.
In the past however, else was only used when all the above if and elifs failed.

Am i getting this idea right, or is there something fundamental i am missing

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!'


That is correct, with loops the else runs after the loop has completed successfully, its almost the opposite of what we normally think of when we thing of if else.

This website does a great job explaining it.


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