Write a program of factorial in python language - Factorial Program In Python - Python Programming - Python Language

Factorial Program In Python



Here's a Python program to calculate the factorial of a number using recursion:

Python Code:

def factorial(n):

    """

    Returns the factorial of the given non-negative integer n.

    """

    if n == 0:

        return 1

    else:

        return n * factorial(n-1)

Here is the Practical of the above program in Jupyter Notebook

# Example usage 

print(factorial(5))  # 120

print(factorial(0))  # 1

The factorial function takes a non-negative integer n as input and returns the factorial of n. If n is 0, the function returns 1 (since 0! is defined to be 1). Otherwise, it computes the factorial recursively as n times the factorial of n-1.

Note that since the factorial grows very quickly, this implementation may cause a "maximum recursion depth exceeded" error if n is too large. In that case, you can use an iterative implementation instead. Here's an example:

Python Code:

def factorial(n):

    """

    Returns the factorial of the given non-negative integer n.

    """

    result = 1

    for i in range(1, n+1):

        result *= i

    return result 

This implementation uses a loop to compute the factorial iteratively, multiplying the result by each integer from 1 to n.

Comments