[Tutor] recursion surprise

Dave Angel davea at davea.name
Sun Jun 9 00:43:03 CEST 2013


On 06/08/2013 05:46 PM, Jim Mooney wrote:
> I was trying out simple recursion as below, with the printout I
> expected, but it then also prints out "None" nine times. How does that
> work?
>
> Jim
>
> #Using Python 3.3.2 on Win 7 - standard project, standard test file
>
> def addone(num):
>      if num > 10:
>          return num
>      num = addone(num + 1)
>
> print(addone(1))
>
> Result:
> 11
> None
> None
> None
> None
> None
> None
> None
> None
> None
>
>

Post the same code that you ran, to get that output.  Otherwise you're 
wasting our time.

Your function is missing a return statement, presumably you meant to 
return num, and presumably that would be directly after you assign to num.

Since you don't have a return statement, when the function falls off the 
end, it returns None.  So this is how your function currently looks 
(before you fix it)

def addone(num):
     if num > 10:
         return num
     num = addone(num + 1)
     return None


-- 
DaveA


More information about the Tutor mailing list