[Tutor] recursive function example
ugajin at talktalk.net
ugajin at talktalk.net
Thu Dec 12 05:18:00 CET 2013
In a way, it may help to identify the issue
def multiply(a,b)
return a*b
clearly returns the product of the two arguments, a and b
I presume it returns a+a rather than b+b+b
mult(a, b-1) also has two arguments.
and rest takes the value of the two arguments, but
I do not see an instruction to multiply the arguments
How in the original def mult(a, b) . . .,
does mult(a, b-1) say return the product of a and b-1?
-----Original Message-----
From: Alan Gauld <alan.gauld at btinternet.com>
To: tutor at python.org
Sent: Thu, 12 Dec 2013 0:27
Subject: Re: [Tutor] recursive function example
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
_______________________________________________
Tutor maillist - Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131211/34cffd1c/attachment.html>
More information about the Tutor
mailing list