[Tutor] returning from a function?

D-Man dsh8290@rit.edu
Sat, 17 Mar 2001 13:39:50 -0500


On Sat, Mar 17, 2001 at 06:45:24PM +1000, Suzanne Little wrote:
| Sorry but I don't have access to the snipped part at the moment. It
| doesn't contain any return statements or print statements. 
<snip>
| Hopefully that makes it clear enough.

It does.  What you have is essentially,

def func( some , args ) :
    if terminating_condition :
        return "some value"
    else :
        # call a function (this one) but DON"T return its return value
        func( some , different_args )


The result is if the condition is not true the first time the function
is called, it won't return anything because that is the only place it
has a return statement.  To correct it, add 'return' in the else
clause to return the value that is returned by the last recursive
call.

def func( some , args ) :
    if terminating_condition :
        return "some value"
    else :
        # call a function (this one) and return its return value
        return func( different , args )

This should solve your problem.


This is a bit different than Lisp or Scheme.  Lisp and Scheme
implicitly return the return value from the last expression in the
function.  So if you had

(def func (some args)
    (if terminating_condition
        "some value"
        (func different args)))

it would have worked as expected, returning "some value" from the last
invocation and propagating it up the stack to the first caller.
(Actually, Scheme is cool because it optimizes tail-recursive
functions like this so that almost all of the stack operations are
eliminated and the last invocation returns directly to the first
caller)

-D