Python recursive function not working

def factorial_recursive(n):
    if n>=0:
      return n * factorial_recursive(n-1)

factorial_recursive(4)

Hi

I am trying out some python code above, to understand recursion ; it is not part of the course , but I wonder why I get an error message and it does not execute?

TypeError: unsupported operand type(s) for *: ‘int’ and ‘NoneType’

2 Likes

If i’m not wrong @jamesberentsen, a function cannot call itself. Not sure if it will work if you nest the function in another and call the outer function though. You can try that out and let me know how it goes…

Hi there,

Are you sure ?
I thought that was the very definition of a recursive function — to call itself:

Hello @jamesberentsen,

If you don’t return anything by default it would retun None which is NoneType and Arithmetic operation between NoneType and int is not possible. ex None * 1

That is why you geting this exception

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

So When your if condition (n>=0) gets False it would return None

2 Likes

Hi DishinGoyaniCommunity Moderator

brilliant , thanks.

1 Like