1

I have encountered a problem where a return gives None back, though the variable had a value just a single line of code before.

mylist = [[7]]

def sumcalc(the_list,n):
    s = n
    for x,y in enumerate(the_list):
        if type(y) == list:
            sumcalc(y,s)
        elif type(y) == int:
            s += y
            if x < len(the_list)-1:
                sumcalc(the_list[x+1], s)
            else:
                print (s)
                return s
    
print(sumcalc(mylist,0))

The print command in the second to last line gives me 7, as expected. But the return is None. Any help on this would be appreciated :)

DuDa
  • 3,718
  • 4
  • 16
  • 36
PeterPefi
  • 87
  • 1
  • 1
  • 7
  • 2
    You have to replace `sumcalc(y,s)` with `return sumcalc(y,s)` – Abdul Niyas P M Jan 23 '21 at 17:14
  • Does this answer your question? [Why does my recursive function return None?](https://stackoverflow.com/questions/17778372/why-does-my-recursive-function-return-none) – wjandrea Jan 23 '21 at 17:49

2 Answers2

1

If you are writing a recursive function. You must put return key word before recursive call.

mylist = [[7]]

def sumcalc(the_list,n):
    s = n
    for x,y in enumerate(the_list):
        if type(y) == list:
            return sumcalc(y,s)
        elif type(y) == int:
            s += y
            if x < len(the_list)-1:
                sumcalc(the_list[x+1], s)
            else:
                print (s)
                return s
    
print(sumcalc(mylist,0))
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103
Aaditya Bhardwaj
  • 362
  • 2
  • 14
0

sumcalc() doesn't do anything on its own; you need to use the return value. Beyond this, the index checking is unecessary, as the return could simply be placed after the loop. Here is a simpler way of writing the nested sum code.

def nested_sum(x):
    if type(x)==int:
        return x
    if type(x)==list:
        return sum(
            nested_sum(item)
            for item in x
        )
Ted Brownlow
  • 1,103
  • 9
  • 15