-3

Recursive function to sum elements in a list is returning None

def recsum(l,sum=0):
    sum += l[0]
    l = l[1:]
    if l:recsum(l,sum)
    else: return sum

val = [2,3,4,5]

print(recsum(val))

Output

None

Prashant Singh
  • 156
  • 1
  • 5

2 Answers2

1

You need to return the function when you call it from inside itself:

def recsum(l,sum=0):
    sum += l[0]
    l = l[1:]
    if l:
        return recsum(l,sum)
    else: 
        return sum
Lord Elrond
  • 13,430
  • 7
  • 40
  • 80
0

Resolved: when l was non-empty then function was returning None so just adding a return statement resolved the issue

def recsum(l,sum=0):
    sum += l[0]
    l = l[1:]
    if l:return recsum(l,sum)
    else: return sum

val = [2,3,4,6]

print(recsum(val))

Output: 15

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Prashant Singh
  • 156
  • 1
  • 5
  • Hey. I did a similar answer but was not able to replicate your solution on my code... Where is the recursion? Why are u returning the function? This isnt clear to me. Sorry. – Raul Chiarella Dec 03 '22 at 23:18