# Trying to understand an error

#1

Hi Stetim

I've got this piece of code for calculating factorials, which works:

``````def factorial(x):
if x > 1:
return x * factorial(x - 1)
else:
return 1``````

``````def factorial(x):
if x > 0:
return x * factorial(x - 1)
else:
return 0``````

Which would always return 0

And even before that I had this:

``````def factorial(x):
if x > 0:
return x * factorial(x - 1)``````

Which would return this error:

``````factorial(10)
Traceback (most recent call last):
File "<pyshell#62>", line 1, in <module>
factorial(10)
File "<pyshell#61>", line 3, in factorial
return x * factorial(x - 1)
File "<pyshell#61>", line 3, in factorial
return x * factorial(x - 1)
File "<pyshell#61>", line 3, in factorial
return x * factorial(x - 1)
[Previous line repeated 6 more times]
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'``````

Could you help me understand why the 2nd function would always return 0 and what the error of the 3rd function is and why it happens?

Thanks a ton

EDIT: I realized the 2nd function would always return 0 because in the last iteration it would return 0 and hence multiply my so far result by 0, resulting in 0.

So only need help with the 3rd function now

EDIT 2: Just figured out that in the 3rd function, once x reached 0, it would return None, which isn't a supported type for multiplication.

This can be closed now
Thanks a lot !

#2

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.