What does "Return" do in Python?

Asked

Viewed 21,117 times

11

What "really" the return does in Python, mainly in recursive functions. Ex. factorial:

def fatorial(n):
    if n==1:
        return n
    return fatorial(n-1) * n
  • 1

    Did any of the answers solve the problem? Do you think you can accept one of them? See [tour] how to do this. You’d be helping the community by identifying the best solution. You can only accept one of them, but you can vote for anything on the entire site.

2 answers

14

As in any language mainstream, the return ends the execution of the current function, returning exactly to the point where it was called.

Eventually it can return a value as a result of the function, ie where the function was called will have the return value used in the expression built there.

There’s nothing special about return when it is used in recursive functions, the functioning is exactly the same. In a recursive function the calls accumulate and the returns occur later always returning to the same point, but in different states. Obviously at some point you need to stop making recursive calls, otherwise you have an infinite recursion and pop the stack.

As it is not a special case, if there is a large number of calls, and each call keeps its own state (values of local variables), it fills the pile of the application and may give such stack overflow.

Some languages/compilers do optimizations to avoid this overflow in cases of too much recursion, which also helps in efficiency.

  • Not any language: http://www-12.lotus.com/ldd/doc/domino_notes/rnext/help6_designer.nsf/f4b82fbb75e942a6852566ac0037f284/cf2d84d26824491585256c54004c65c5?OpenDocument . Perhaps any language worth its salt. =/

  • 2

    Ah, the mainstream, right? :)

4

It returns the value of the function. In the specific case of recursive functions, it, besides returning the value (which can also be a null value None), will also return the control flow to the caller function.

  • 1

    The return of the control flow to the calling function happens even in non-recursive functions.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.