def factorial(n):
if n<=1:
return_value=1
print(return_value)
else:
return_value=n*(factorial(n-1))
print(return_value)
factorial(10)
the error is:
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
CodePudding user response:
Issue with your code is that you're not returning any value at the end of function call. So in the statement return_value=n*(factorial(n-1))
where you are expecting 10*factorial(9)
you're getting return_value=10*None
which results in Invalid operation as you can see in the error
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
As * doesn't work with None
and int
as operand.
Solution is simple add a return statement
def factorial(n):
if n<=1:
return_value=1
print(return_value)
else:
return_value=n*factorial(n-1)
print(return_value)
return return_value
factorial(10)
CodePudding user response:
First of all your factorial program is incorrect that is not my concern if you ask me then I will tell you now come to the main point, whenever the function is used you can return something so it can show an output, as your input value and function take that value and apply functionalities but after completion function doesn't know how it can return your result. so the return keyword helps to do it.
def factorial(n):
if n<=1:
return_value=1
print(return_value)
return return_value
else:
n=n*factorial(n-1)
print(n)
return n
factorial(10)