Adding through recursion

Rocco Moretti roccomoretti at hotpop.com
Fri Nov 18 17:33:14 CET 2005


martin.clausen at gmail.com wrote:
> There is problaly a really simple answer to this, but why does this
> function print the correct result but return "None":
> 
> def add(x, y):
>     if x == 0:
>         print y
>         return y
>     else:
>         x -= 1
>         y += 1
>         add(x, y)
> 
> print add(2, 4)

One of the best things to do when you don't understand how a function is 
working is to geneously sprinkle the code with tracing print statements:

 >>> def add(x, y):
     params = (x, y)
     print "Starting Function", params
     if x == 0:
	print "x is zero", params
         print y
         return y
	print "After Return", params
     else:
	print "Non-zero x", params
         x -= 1
         y += 1
         print "Updated x & y", params, '->', (x,y)
         add(x, y)
         print "Should I be here?", params
     print "Falling off end.", params


 >>> print add(2, 4)
Starting Function (2, 4)
Non-zero x (2, 4)
Updated x & y (2, 4) -> (1, 5)
Starting Function (1, 5)
Non-zero x (1, 5)
Updated x & y (1, 5) -> (0, 6)
Starting Function (0, 6)
x is zero (0, 6)
6
Should I be here? (1, 5)
Falling off end. (1, 5)
Should I be here? (2, 4)
Falling off end. (2, 4)
None



More information about the Python-list mailing list