Python Program to Find Factorial of Number Using Recursion

1. Introduction

In this tutorial, we will learn how to write a Python program to find the factorial of a number using recursion.

Factorial of a number is a common mathematical operation with applications in statistics, combinatorics, and algebra. In programming, calculating a factorial provides a clear example of how recursion can be applied to solve problems.

The factorial of a non-negative integer n is the product of all positive integers less than or equal to n, denoted by n!. By convention, the factorial of zero is one. The recursive definition of factorial is n! = n × (n−1)! with the base case 0! = 1.

2. Program Steps

1. Define a function that calculates the factorial using recursion.

2. If the number is zero, return one (base case).

3. Otherwise, return the number multiplied by the factorial of the number minus one.

4. Call the recursive function with the desired number.

5. Print the result.

3. Code Program

# Recursive function to find the factorial of a number
def factorial(n):
    # Base case: the factorial of 0 is 1
    if n == 0:
        return 1
    # Recursive step: n! = n * (n-1)!
    else:
        return n * factorial(n-1)

# Number to find the factorial of
number = 5
# Calculate and print the factorial
print(f"The factorial of {number} is: {factorial(number)}")

Output:

The factorial of 5 is: 120

Explanation:

1. factorial is a function that accepts an integer n.

2. It checks if n is 0, in which case it returns 1 according to the definition of factorial (base case).

3. If n is not 0, it performs a recursive call to factorial(n-1) and multiplies the result by n.

4. The process of calling factorial continues until the base case is reached, after which all the recursive calls return, cumulatively multiplying the integers from n down to 1.

5. The final result of factorial(5) is 120, which is the product of 5 4 3 2 1.

6. The output is then printed, indicating that the factorial of 5 is 120.

Comments