what is the difference between return and break in python?

Question:

what is the difference between return and break in python?
Please explain what they exactly do in loops and functions?
thank you

Asked By: user4374379

||

Answers:

return would finish the whole function while break just make you finish the loop

Example:

def test_return()
    for i in xrange(3):
        if i==1:
            print i
            return i
    print 'not able to reach here'


def test_break()
    for i in xrange(3):
        if i==1:
            print i
            break
    print 'able to reach here'

test_return()  # print:  0 1
test_break()  # print:  0 1 'able to reach here'   
Answered By: Paul Lo

break is used to end loops while return is used to end a function (and return a value).

There is also continue as a means to proceed to next iteration without completing the current one.

return can sometimes be used somewhat as a break when looping, an example would be a simple search function to search what in lst:

def search(lst, what):
    for item in lst:
        if item == what:
            break

    if item == what:
        return item

And nicer, equivalent function, with return:

def search(lst, what):
    for item in lst:
        if item == what:
            return item # breaks loop

Read more about simple statements here.

At the instruction level you can see the statements do different things:

return just returns a value (RETURN_VALUE) to the caller:

    >>> import dis
    >>> def x():
    ...     return
    ... 
    >>> dis.dis(x)
      2           0 LOAD_CONST               0 (None)
                  3 RETURN_VALUE        

break stops a the current loop (BREAK_LOOP) and moves on:

>>> def y():
...     for i in range(10):
...         break
... 
>>> dis.dis(y)
  2           0 SETUP_LOOP              21 (to 24)
              3 LOAD_GLOBAL              0 (range)
              6 LOAD_CONST               1 (10)
              9 CALL_FUNCTION            1
             12 GET_ITER            
        >>   13 FOR_ITER                 7 (to 23)
             16 STORE_FAST               0 (i)

  3          19 BREAK_LOOP          
             20 JUMP_ABSOLUTE           13
        >>   23 POP_BLOCK           
        >>   24 LOAD_CONST               0 (None)
             27 RETURN_VALUE  
Answered By: Reut Sharabani

Return will exit the definition at the exact point that it is called, passing the variable after it directly out of the definition. Break will only cause the end of a loop that it is situated in.

For example

def Foo():
    return 6
    print("This never gets printed")

bar = Foo()

That will make bar equal to six. The code after the return statement will never be run.

The break example:

def Loop():
    while True:
        print("Hi")
        break

Loop()

That will print only once, as the break statement will cause the end of the infinite while loop.

Let’s take a look at an example:

def f(x, y):
    n = 0
    for n in range(x, y):
         if not n % 2: continue
         elif not n % 3: break
    return n
print((f(1, 10)))

This prints 3. Why? Let’s step through the program:

def f(x, y):

define a function

    n = None

set variable ‘n’ to None

    for n in range(x, y):

begin iterating from ‘x’ to ‘y’. in our case, one through nine

         if not n % 2: continue

discontinue this iteration if ‘n’ is evenly divisible by two

         elif not n % 3: break

leave this iteration if n is evenly divisible by three

    return n

our function ‘f’ “returns” the value of ‘n’

print((f(1, 10)))

‘f(1, 10)’ prints three because it evaluates to ‘n’ once execution leaves the scope of the function

Answered By: motoku

break is used to end a loop prematurely while return is the keyword used to pass back a return value to the caller of the function. If it is used without an argument it simply ends the function and returns to where the code was executing previously.

There are situations where they can serve the same purpose but here are two examples to give you an idea of what they are used for

Using break

Iterating over a list of values and breaking when we’ve seen the number 3.

def loop3():
    for a in range(0,10):
        print a
        if a == 3:
            # We found a three, let's stop looping
            break
    print "Found 3!"

loop3()

will produce the following output

0
1
2
3
Found 3!

Using return

Here is an example of how return is used to return a value after the function has computed a value based on the incoming parameters:

def sum(a, b):
    return a+b

s = sum(2, 3)
print s

Output:

5

Comparing the two

Now, in the first example, if there was nothing happening after the loop, we could just as well have used return and "jumped out" of the function immediately. Compare the output with the first example when we use return instead of break:

def loop3():
    for a in range(0, 6):
        print a
        if a == 3:
            # We found a three, let's end the function and "go back"
            return

    print "Found 3!"

loop3()

Output

0
1
2
3
Answered By: Parham

I will try to illustrate it with an example:

def age_to_find_true_love(my_age):
    for age in range(my_age, 100):
        if find_true_love_at(age):
            return age

        if age > 50:
            break

    return "...actually do you like cats?"
Answered By: d.raev
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.