Bård
Bård

Reputation: 57

Trying to add numbers with a function

def listsum(numList):
    if len(numList) == 1:
        print(numList[0])
    else:
         print(numList[0]+listsum(numList[1:]))
    
if __name__ == '__main__':
    lit1=[1, 2,  3, 4, 5]
    listsum(lit1)
    

I need help with this code, I am getting:

TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'.

I am trying to add all the enumbers in a list

Upvotes: 1

Views: 91

Answers (1)

Mureinik
Mureinik

Reputation: 311188

Instead of printing the sum, you should just return it, and leave the printing to the caller:

def listsum(numList):
    if len(numList) == 1:
        return numList[0]
    else:
         return numList[0] + listsum(numList[1:])
    
if __name__ == '__main__':
    lit1=[1, 2,  3, 4, 5]
    print(listsum(lit1))

Upvotes: 1

Related Questions