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


#1




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


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?


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


#2

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

appylpye does an excellent job of explaining it


#3

@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

#4

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