简体   繁体   中英

Function returns none instead of the sum of list

Why does this code return none in Python 2? However if I replace return statement with print statement ie 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)

You need to

return cal(arr)

otherwise the function will just call itself recursively and return None by default (instead of the calculated result).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM