[Tutor] recursion surprise

Dave Angel davea at davea.name
Sun Jun 9 02:28:17 CEST 2013


On 06/08/2013 07: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?
>
> Jim
>
>

Since your function has more than one return point, you need more than 
one return statement, or you'll wind up with the default one, which is None.

Try a simpler function, and see if you can get it straight.

def  newfunc(x):
     if x > 5:
         return x+20
     else:
         pass
         # return x+100

What would you expect it to return for x <= 5.  Without the extra return 
statement, it's going to return None.  Test it for yourself:

print newfunc(7)
print newfunc(3)


By the way, the empty return statement also returns None.

-- 
DaveA


More information about the Tutor mailing list