DEV Community

Afiz
Afiz

Posted on

Find the factorial of given number in Python

Method 1: Finding the factorial of a given number using for loop

def factorial(number):
    output = 1
    if number < 2:
        return output
    else:
        for i in range(2, number+1):
            output *= i
    return output

print(factorial(5))

# output: 120

Enter fullscreen mode Exit fullscreen mode

Method 2: Finding the factorial of a given number using recursion

def factorial_recursion(number):
    if number < 2:
        return 1
    return number * factorial_recursion(number -1)def factorial_recursion(number):
    if number < 2:
        return 1
    return number * factorial_recursion(number -1)

print(factorial_recursion(5))

# output: 120
Enter fullscreen mode Exit fullscreen mode

Method 3: Finding the factorial of a given number using the lambda function

factorial_lambda = lambda number: 1 if number  < 2 else  number * factorial_lambda(number -1)

print(factorial_recursion(5))

# output: 120
Enter fullscreen mode Exit fullscreen mode

Thanks for reading this post. Let me know which one is your favorite method.

Top comments (0)