def fact(n, summ):
if n == 0:
print(summ) -- Prints 55
return summ
fact(n-1, summ + n)
print(fact(10, 0)) -- Output None
Asked
Active
Viewed 33 times
-1
-
2You need to use `return fact(n-1, summ + n)` – Rakesh Jul 01 '18 at 15:32
-
Yes I understand, but why does it return 'None' if I return it from inside the IF block ? – Dhruv Jul 01 '18 at 15:35
-
@Dhruv The linked question has answers for your query. – Austin Jul 01 '18 at 15:38
-
@Dhruv Because it only returns from the block when `n == 0`, so `None` is implicitly returned if nothing else is. Think of the flow of data between recurses. Every path of execution must return something or that data is lost. – Carcigenicate Jul 01 '18 at 16:01
-
@Carcigenicate: Thanks, got the point. So silly of me. – Dhruv Jul 01 '18 at 16:37
1 Answers
1
You need to return fact(n-1, summ + n)
as a returning value. If a function does not return a value then it defaults to returning None.
def fact(n, summ):
if n == 0:
return summ
return fact(n-1, summ + n)
print(fact(10, 0))
This outputs:
55
On a side note, your fact
function could be re-implemented without the second parameter. The following produces the same output:
def fact(n):
if n == 0:
return 0
return n + fact(n-1)
print(fact(10))

blhsing
- 91,368
- 6
- 71
- 106