I am totally new to recursive functions and tried to create a function to compute the factorial of n. In my example I assume n > 0.
def myfactorial(n):
if (n - 1) > 0: # Check if n - 1 is > 0
return ( n * myfactorial(n - 1) ) # Then multiply current n with myfactorial(n - 1)
else:
return # If condition is false, then stop function
However, it the error unsupported operand type(s) for *: 'int' and 'NoneType'
for the line return ( n * myfactorial(n - 1) )
.
When looking at the solution from w3resource.com
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
They use the same return idea in the statement as I.
Can anyone tell me what is wrong in my approach (by the way, I designed the if statement on purpose as n-1 > 0, nevertheless it has to work with this statement as well)?
Many thanks for your help!
CodePudding user response:
When you write return
it's have the same effect as return None
.
When you do myfactorial(1)
, you return None
. With myfactorial(2)
, you do 2 * myfactorial(1)
, which is equivalent to 2 * None
, which trigger the error :
unsupported operand type(s) for *: 'int' and 'NoneType'
That why you have to write return 1
in your else branch.