Loop Else vs Regular Else


#1



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.)
        break
    print 'A', f

else:
    print 'A fine selection of fruits!'


#2

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.
http://python-notes.curiousefficiency.org/en/latest/python_concepts/break_else.html


#3

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