[Tutor] recursive function example

ugajin at talktalk.net ugajin at talktalk.net
Tue Dec 10 15:48:55 CET 2013


I am looking at a simple recursive function, and oxymoron aside, I am having difficulty in seeing what occurs. I have tried adding some debug print commands to help break the thing down. This helps a lot, but I still have a question that I need help with.

Here is original code:
def mult(a, b):
    if b == 0:
        return 0
    rest = mult(a, b - 1)
    value = a + rest
    return value
print "3 * 2 = ", mult(3, 2)

I see how python outputs the string "mult(3,2)" before running the function, 
and then adds the return value to the output, 
and I see how the 'if' condition is met, 
but I do not see how the variable 'rest' is assigned a value, and a single value at that. 
'rest' must have a value of 3 (for this example) for the function to return the correct 
value, and 'rest' must be assigned the value of '3' but when, prior, to b == 0?
When 'b' == 0 (zero) the 'if' condition is escaped.
In the first iteration, 'rest' is shown with the value '0' (zero), 
and in the second it is '3'.
1st, run rest = mult(3, 1)
2nd. run rest = mult(3, 0) and the 'if' condition is met
Is there some inherent multiplication e.g. 3*1 = 3 and 3*0 = 0, 
and even if so, it seems backwards?

I am once again perplexed!
Help please. . . if you can.

-A

Here is my debugging code:

#! /usr/bin/env python

def mult(a, b):
    if b == 0:
        return 0
    print
    print 'a =', a
    print 'b =', b
    rest = mult(a, b - 1)
    print
    print 'rest =', rest
    value = a + rest
    print 'value =', value, '(a + rest ==',a, '+', rest,')'
    return value
print
print 'mult(3,2) value = ', '\n', '\nreturn = ' + str(mult(3, 2))


Here is the output from the debugging code:

mult(3,2) value =  

a = 3
b = 2

a = 3
b = 1

rest = 0
value = 3 (a + rest == 3 + 0 )

rest = 3
value = 6 (a + rest == 3 + 3 )

return = 6



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131210/02d8f8a8/attachment.html>


More information about the Tutor mailing list