How to Calculate the Factorial of a Number Using Python

In this blog, I will show how to calculate the factorial of a number using Python with a simple 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!. For example:

  • 5!=5×4×3×2×1=120
  • 0!=1 (by definition)

The factorial of n can be expressed mathematically as:

Factorial

Below is a Python program to calculate the factorial of a given number using a recursive function:

import sys

def factorial(n):
    # Base case: factorial of 0 or 1 is 1
    if n == 0 or n == 1:
        return 1
    # Recursive case
    return n * factorial(n - 1)

def main():
    """
    this program calculates the factorial of a given number
    """
    # provide the number as command-line argument
    args = sys.argv
    # check if user provided a number or not
    if len(args) < 2:
        print("no number provided")
    else:
        num = int(args[1])
        if num < 0:
            print("the number should be >=0")
        else:
            print(f"factorial of {num} is {factorial(num)}.")

if __name__ == "__main__":
    main()

Save the above code as facto.py (or any name you like) and run it as follows:

python facto.py 10

Replace 10 with your desired number and the code will return factorial for your number.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.