[Tutor] recursion surprise

Don Jennings dfjennings at gmail.com
Sun Jun 9 02:10:24 CEST 2013


On Jun 8, 2013, at 7:52 PM, Jim Mooney wrote:

> On 8 June 2013 16:46, Dave Angel <davea at davea.name> wrote:
>> On 06/08/2013 07:12 PM, Jim Mooney wrote:
>>> 
>>> On 8 June 2013 15:43, Dave Angel <davea at davea.name> wrote:
>> Did you even read my message?  Or Mark's?  Or look at the code I posted?
>> You are missing a return statement at the end of the function, so after the
>> assignment  num=addone(num+1) it will return None, by definition.
> 
> Well, I thought
> 
>    if num > 10:
>        return num
> 
> Was a return statement. Num does become > 10.   You mean I need more than one?

Yes, you do need more than one. Let's walk through your code so you understand what's happening. However, I'll take the liberty of changing the if test so we go through only one level of recursion.

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

print(addone(1))

So, what happens on the first call?

addone(num)  # num is the name for the value 1
    if num > 1:  # num is not greater than one; there's no loop, so this check never happens again
        return num  # skip this line
    num = addone(num + 1) # recursive call --> |      addone(num)  # num is now 2, right?
                                               |          if num > 1: # why, yes it is
                                               |              return num # passes back 2 

As Dave pointed out, the function ends, and implicitly returns None since you didn't tell it to return anything else. Does that help?

Take care,
Don



More information about the Tutor mailing list