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

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/courses/python-intermediate-en-rCQKw

<In what way does your code behave incorrectly? Include ALL error messages.>
I do this exercise with this code (and its works):

def factorial(x):
    total = 0
    if x == 1 or x == 0:
        return 1
    else:
        total = x * factorial(x - 1)
        return total

<What do you expect to happen instead?>
But i want to know does it really work by giving parameters
And i got this error:

Traceback (most recent call last):
File “python”, line 7, in
File “python”, line 6, in factorial
TypeError: unsupported operand type(s) for *: ‘int’ and ‘NoneType’

how fix to fix that?

```python

def factorial(x):
total = 0
if x == 1 or x == 0:
return 1
else:
total = x * factorial(x-1)
print factorial(3)

<do not remove the three backticks above>

a recursive solution is difficult to understand, please read here:

appylpye does an excellent job of explaining it

1 Like

@bestboy120 ,

For the Practice Makes Perfect: factorial exercise, a recursive solution works, but the factorial function must return a value for the base case and for the recursive case. You have this as a second example …

def factorial(x):
    total = 0
    if x == 1 or x == 0:
        return 1
    else:
        total = x * factorial(x-1)
print factorial(3)

For the base case, implemented in your function as …

    if x == 1 or x == 0:
        return 1

… the function does correctly return a result of 1.

However, you have this as the recursive case …

    else:
        total = x * factorial(x-1)

There is no return statement in the else block and neither is there one after the block to return the value of total.

There are several ways to correct this. This one omits the total variable, since it is not needed …

def factorial(x):
    if x == 1 or x == 0:
        # base case
        return 1
    else:
        # recursive case
        return x * factorial(x - 1)

print factorial(3)

Output …

6
1 Like

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