Python program that uses recursion to find the factorial of a given number:

Created with Sketch.

Python Program: Recursion to Find Factorial

Recursion is a powerful programming concept where a function calls itself, and it’s often used to solve problems that can be broken down into smaller, identical subproblems. In this blog post, we’ll explore a Python program that uses recursion to find the factorial of a given number. The post will provide a comprehensive explanation along with a step-by-step guide and example outputs.

Understanding Factorial

The factorial of a non-negative integer n, denoted as n!, is the product of all positive integers less than or equal to n. Mathematically, it’s defined as:

Python Program: Factorial using Recursion

Let’s proceed with the Python program. The example includes a function named calculate_factorial that recursively calculates the factorial of a given number.

def calculate_factorial(num):
    if num == 0 or num == 1:
        return 1
    else:
        return num * calculate_factorial(num - 1)

# Get user input
number = int(input("Enter a non-negative integer: "))

# Check for negative input
if number < 0:
    print("Factorial is undefined for negative numbers.")
else:
    result = calculate_factorial(number)
    print(f"The factorial of {number} is: {result}")

Example Usage

  1. Run the Python program:

python factorial_recursive.py

2. Enter a non-negative integer when prompted. The program will then calculate and display the factorial.

Example Outputs

  • Factorial of 5:

Enter a non-negative integer: 5
The factorial of 5 is: 120

Factorial of 0:

 
Enter a non-negative integer: 0
The factorial of 0 is: 1

Factorial of 10:

 
Enter a non-negative integer: 10
The factorial of 10 is: 3628800

Step-by-Step Explanation

  1. Function calculate_factorial():

    • The function takes an integer parameter (num) and recursively calculates the factorial.
    • The base case checks if num is 0 or 1, in which case the factorial is 1.
    • If num is greater than 1, the function multiplies num by the factorial of (num - 1).
  2. User Input:

    • The program uses input to obtain user input for a non-negative integer.
  3. Negative Number Check:

    • The program checks if the input is negative and prints a message if so.
  4. Result Display:

    • If the input is non-negative, the program calculates and prints the factorial.

Conclusion

Recursion is a powerful technique in programming, and calculating the factorial of a number is a classic problem to showcase its application. Understanding recursion not only helps in solving specific problems but also enhances problem-solving skills in general. As you explore this Python program, consider how recursion simplifies the solution to a problem that can be divided into smaller, similar subproblems.

Leave a Reply

Your email address will not be published. Required fields are marked *