JackPot
JackPot

Reputation: 25

Why am I getting TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

def tri_recursion(k):
    
    if (k > 0):
        result = k + tri_recursion(k - 1)
        print(result)
    else:
        result = 0
        return result
        
tri_recursion(6)

So when I shift the 'return result' statement in line 7 to the left just under the else statement, I get the correct output. But when I keep the code as shown, I get the following error:

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

Why is that?

Upvotes: 0

Views: 51

Answers (1)

oskros
oskros

Reputation: 3305

Your recursive function is not returning anything when k>0, thus implicitly returning None

Try the below

def tri_recursion(k):
    
    if (k > 0):
        result = k + tri_recursion(k - 1)
        print(result)
        return result
    else:
        result = 0
        return result
        
tri_recursion(6)

Upvotes: 2

Related Questions