Factorial Calculation in Python

This document explains how to calculate the factorial of a given number using a Python program. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted as n! and is defined as:

        n! = n * (n-1) * (n-2) * ... * 1

Python Program

The following Python program calculates the factorial of a given number using a recursive function:

def factorial(n):
    """
    Calculate the factorial of a given number n.

    Args:
        n (int): The number to calculate the factorial for.

    Returns:
        int: The factorial of the number n.

    Raises:
        ValueError: If n is a negative integer.
    """
    if n < 0:
        raise ValueError("Factorial is not defined for negative numbers.")
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)

# Example usage
if __name__ == "__main__":
    try:
        number = int(input("Enter a number to calculate its factorial: "))
        result = factorial(number)
        print(f"The factorial of {number} is {result}.")
    except ValueError as e:
        print(e)

Explanation

The factorial function is defined to calculate the factorial of a non-negative integer n. The function follows these steps:

  • If n is less than 0, it raises a ValueError because the factorial is not defined for negative numbers.
  • If n is 0 or 1, the function returns 1 because 0! = 1 and 1! = 1 by definition.
  • For other values of n, the function recursively calls itself with n-1 and multiplies the result by n.

The example usage section prompts the user to enter a number and then calculates and prints its factorial.

How to Run the Program

To run the program, copy the Python code into a file named factorial.py and execute it using a Python interpreter. For example:

python factorial.py

When prompted, enter a non-negative integer to see the factorial calculation result.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)