[Tutor] recursive function example

Alan Gauld alan.gauld at btinternet.com
Thu Dec 12 01:23:30 CET 2013


On 11/12/13 18:09, ugajin at talktalk.net wrote:
>
> No, not really.
> mutl(3, 2) has two arguments
> rest = mult(a, b - 1) also has two arguments

rest does not have any arguments.
arguments are the values you pass *into* a function.
The function in turn passes back a return value.

In this case rest is assigned the return value
from mult(a, b-1) Note that this is an entirely
*separate* call to mult() from the one in whose
code it appears. The fact that mult() is calling
(another copy) of mult() is what makes it recursive.

But the function call is just like any other.
The first call to mult(3,2) results in another
call to mult(3,1) but there is no communication
or connection between those two calls to mult()
except the arguments passed in (3,1 and the
value returned, 3.

The outer, calling, mult simply waits for the
inner call to mult to complete and return its
value, just like any other function,

Let me put it this way. Lets ignore the fact
that mult calls mult and define a new function
called multiply:

def multiply(a,b):
    return a*b

def mult(a,b):
    if b == 0:
      return 0
    rest = multiply(a, b-1)
    value = a + rest
    return value

Can you understand that?

The recursive function works *exactly* like
that except that instead of calling multiply
it calls itself.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list