What is the difference between break and return?

Question

What is the difference between break and return?

Answer

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.

7 Likes

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 :point_down: (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 :point_down: (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!'

It’s to understand…

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.

1 Like

for..else is a far cry from if..else.

In the latter, else is connotative of, “in any case…”. In the former, else is connotative of, “not wanted on the voyage”.

In either case, neither satisfied their condition.

1 Like