Python Program to Calculate Factorial of Any Number Using Recursive Function

Posted by

Calculating Factorials in Python

Calculate the factorial of any number using recursive function in Python

Factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted by n! and is calculated as n! = n*(n-1)*(n-2)*…*1.

One way to calculate the factorial of a number in Python is by using a recursive function. A recursive function is a function that calls itself until a certain condition is met. In the case of calculating factorials, the base case would be when the number is equal to 1.

Here is an example of a recursive function in Python to calculate the factorial of any number:

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

number = 5
result = factorial(number)
print(f"The factorial of {number} is {result}")
    

When you run this code with number = 5, the output will be “The factorial of 5 is 120”. This is because 5! = 5*4*3*2*1 = 120.

You can try running this code with different values for ‘number’ to calculate the factorial of any number you want.

Using recursive functions to calculate factorials is a simple and elegant way to solve this problem in Python. It is important to remember to include a base case in the recursive function to prevent infinite recursion.