[Tutor] Function returns 'None'

Adam Bark adam.jtm30 at gmail.com
Sun Jul 11 16:46:40 CEST 2010


On 11/07/10 14:59, Dominik Danter wrote:
> Hello
>
> As en exercise I wrote the following function:
>
>
> def recursfac(x,carryover=1):
>     print 'x:',x,'carryover:', carryover
>     if x > 1:
>         carryover *= x
>         recursfac(x-1, carryover)
>     else:
>         return carryover
>
> print recursfac(3)
>
> Very much to my surprise I get the following output:
>
> x: 3 carryover: 1
> x: 2 carryover: 3
> x: 1 carryover: 6
> None
>
> Where did I go wrong?
>
> Kind regards
> Dominik Danter

I made a diagram to try to explain

recursfac(3)
     recursfac(2, 3) <----|
         recursfac(1, 6)  _|

As you can see recursfac(1,6) returns it's value (carryover) to 
recursfac(2, 3) which ignores it and completes it's execution ie 
returning None to your original call which then prints out that return 
value.
I hope that's clear.

Adam.


More information about the Tutor mailing list