Search code examples
pythonfactorial

making factorial code with python what's the problem,?


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

The first code has an error but the second function runs properly what is the difference between the two programs? what is the problem with the first code? thank you


Solution

  • The problem is that when the first code evaluates for n<=1, there is no returned value. This causes the function to (by default) return None. Now while evaluating for 2, the program says

    return n* factorial(n-1)
    

    That is equivalent to;

    return 2*None #Since factorial(1)=None
    

    Hence It gives an error as NoneType cannot be multiplied by an integer