Reputation: 51
Why does this code return none in Python 2? However if I replace return statement with print statement i.e print sum in the function itself, it gives the right answer. Why is that so? I know it is a silly question but i cant figure it out on my own.
import math
n=int(raw_input().strip())
temp = [5]
arr=[]
def cal(arr):
arr.append(int(math.floor(temp[-1]/2)))
temp.append(arr[-1]*3)
if len(arr)==n:
return sum(arr)
cal(arr)
print cal(arr)
Upvotes: 0
Views: 1153
Reputation: 8301
You need to
return cal(arr)
otherwise the function will just call itself recursively and return None
by default (instead of the calculated result).
Upvotes: 4
Reputation: 61042
The end of the function should read
if len(arr)==n:
return sum(arr)
else:
return cal(arr)
shouldn't it? You get None
as a return value if your function ends without returning a value.
Upvotes: 2