Search code examples
pythonsyntax-errorgoogle-colaboratory

If-else in single statement vs loop


n = int(input())

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

factorial(n)

The code above works fine but the code below does not. Help please?

n = int(input())

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

factorial(n)

Solution

  • To solve your problem just return the value inside the else:

    n = int(input())
    
    def factorial(n):
        print(n)
        if n < 1:
            return 1
        else:
            return n * factorial(n-1)
    
    factorial(n)