break is used to prematurely end a loop, like we have done a few times throughout this lesson. return is only usable in functions and returns a value to wherever the function was called in the program. If you try using return outside of a function you will get an error.
Please I don’t understand very well the existence of an else after a for loop.
What would be the difference if I wrote:
This (with else)
`fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']`
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!'
and This (without else)
`fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']`
for f in fruits:
if f == 'tomato':
print 'A tomato is not a fruit!' # (It actually is.)
break
print 'A', f
print 'A fine selection of fruits!'
In your first example, the print 'A fine selection of fruits!' statement will only execute if the for loop iterates through the entire fruits array which it won’t because of the break statement. If you remove 'tomato' from the array, the break will never be reached, and the code inside the else: block will execute. In your second example without the else, print 'A fine selection of fruits!' will always execute whether there is a 'tomato' in the array or not.