-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
  • 116
  • 1
  • 4

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
  • 10,935
  • 6
  • 28
  • 60
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
  • 23,210
  • 7
  • 49
  • 68
Prashant Singh
  • 116
  • 1
  • 4