Factorial Calculator in Python

Factorial Calculator in Python

06 Jul 2025
Beginner
2.13K Views
17 min read
Learn with an interactive course and practical hands-on labs

Free Python Programming Course For Beginners

The factorial calculator in Python is a common programming exercise for beginners and professionals alike. It involves calculating the factorial of a number, which is the product of all positive integers up to that number.

In this Python Tutorial, we’ll explore various methods to write a factorial program in Python using for loop, while loop, recursion, and functions. We will also discuss how to write a factorial program without functions and how to take user input for more dynamic results.

What is factorial?

The factorial of a number is the multiplication of all the numbers between 1 and the number itself. It is a mathematical operation written like this: n!. It's a positive integer. Factorial is not defined for negative numbers.

For example, the factorial of 3 is 3! (= 1 × 2 x 3).

Read More: Top 50 Python Interview Questions and Answers

How to calculate the factorial of a number in Python?

1. Using While Loop/Iterative approach

Factorial Program in Python provides another way to calculate the factorial of a number. It continues executing as long as a specified condition is true. This method can be particularly useful when the number of iterations isn’t predetermined:

def factorial(n):
    if n < 0:
           print("Sorry, factorial is undefined for negative numbers")
    elif n == 0 or n == 1:
        return 1
    else:
        fact = 1
        while(n > 1):
            fact *= n
            n -= 1
        return fact

num = 8
print("Factorial of",num,"is",
factorial(num))   

In the above code, we check if the number is negative, zero, or positive using the if...elif...else statement. If the number is positive, we use the while loop in python to calculate the factorial.

iterationfact*i (returned value)
18*1=8
28*7=56
356*6=336
4336*5=1680
51680*4=6720
66720*3=20160
720160*2=40320
840320*1=40320

Output

Factorial of 8 is 40320

Explanation:

  • If n is negative, it prints an error message (factorials are undefined for negatives).
  • If n is 0 or 1, it returns 1 (by definition of factorial).
  • Otherwise, it uses a while loop to multiply n down to 1 to compute the factorial.

Time Complexity:O(n)

  • Because the loop runs from n down to 1, doing a constant-time multiplication at each step.

Space Complexity: O(1)

  • It uses only a constant amount of extra space (fact, n), regardless of the input size.

2. Using Recursion

In Python, recursion is a powerful tool for solving factorial problems elegantly. A factorial program in Python using recursion defines a function that calls itself to compute the result. This approach mimics the mathematical definition of a factorial:

def factorial(n):
    
    # single line to find factorial
    return 1 if (n==1 or n==0) else n * factorial(n - 1) 

# Driver Code
num = 5
print("Factorial of",num,"is",factorial(num))

In the above code, factorial() is a recursive function that calls itself. Here, the function will recursively call itself by decreasing the value of the num.

Output

Factorial of 8 is 40320
Read More: Recursion in Data Structures

Explanation:

  • The function calculates the factorial of a number using recursion.
  • If the input n is 0 or 1, it directly returns 1 (this is the base case).
  • For any other positive integer n, the function calls itself with n - 1.
  • The result is calculated by multiplying n by the factorial of n - 1, building up until the base case is reached.
  • This continues until the recursive calls unwind and return the final result.

Time Complexity: O(n)

  • The function calls itself n times (from n down to 1), doing a constant-time multiplication at each step.

Space Complexity: O(n)

  • Each recursive call consumes stack space.

So for input n, there are n function calls on the call stack, leading to linear space usage.

3. Using One line Solution (Using Ternary operator)


def factorial(n):

    # single line to find factorial
    return 1 if (n==1 or n==0) else n * factorial(n - 1) 

num = 8
print ("Factorial of",num,"is",
      factorial(num))

Output

Factorial of 8 is 40320
Read More: What are Operators in Python?

4. Using Function

Writing a factorial program in Python using a function helps encapsulate the logic in a reusable block of code. Whether you’re using loops or recursion, defining a function enhances code readability and reusability.

import math

def factorial(n):
    return(math.factorial(n))

num = 8
print("Factorial of", num, "is",
      factorial(num))

In the above code, we've used the math module that contains the math.factorial() function to calculate the factorial of any given number.

Output

Factorial of 8 is 40320
Read More: Python Functions - A Complete Guide

Explanation (No Code):

  • This version imports Python's math module.
  • It uses math.factorial(n) to compute the factorial of n.
  • The factorial() function is simply a wrapper around math.factorial().

Time Complexity: O(n)

  • Internally, math.factorial() still performs a loop or efficient multiplication strategy (like binary splitting), which is at least linear in nature.

Space Complexity: O(1)

  • Since it’s written in C, it’s memory-efficient and does not use Python's call stack.
  • It uses constant space from the perspective of Python code (no recursion, no large data structures).

5. Using numpy.prod


import numpy
num=8
fact=numpy.prod([i for i in range(1,num+1)])
print("Factorial of", num, "is",
      fact)

In the above code, we've used the numpy module that contains the numpy.prod() function to calculate the factorial of any given number.

Output

Factorial of 8 is 40320

Explanation:

  • The code uses NumPy's prod() function to compute the product of a list of numbers from 1 to num (inclusive).
  • [i for i in range(1, num+1)] creates a list of numbers from 1 to num.
  • numpy.prod() multiplies all elements in the list together to return the factorial.
  • This is an iterative approach but leverages NumPy's optimized internal functions.

Time Complexity: O(n)

  • Creating the list takes O(n).
  • numpy.prod() iterates over n elements to compute the product → O(n).

Space Complexity: O(n)

  • The list [1, 2, ..., n] takes O(n) space.
  • However, if NumPy is given an array instead of a list generator, it can be more memory-efficient.

6. Using the Prime Factorization Method


def primeFactors(n):
    factors = {}
    i = 2
    while i*i <= n:
        while n % i == 0:
            if i not in factors:
                factors[i] = 0
            factors[i] += 1
            n //= i
        i += 1
    if n > 1:
        if n not in factors:
            factors[n] = 0
        factors[n] += 1
    return factors

# Function to find factorial of a number
def factorial(n):
    result = 1
    for i in range(2, n+1):
        factors = primeFactors(i)
        for p in factors:
            result *= p ** factors[p]
    return result

num = 8
print("Factorial of", num, "is", factorial(num))

Output

Factorial of 8 is 40320

Explanation (No Code):

primeFactors(n) function:

  • Finds the prime factorization of a number n.
  • Uses trial division from i = 2 up to √n to check if i divides n.
  • Stores each prime factor and its exponent in a dictionary.
  • IIf n is still greater than 1 after the loop, it’s a prime and added to the dictionary.

factorial(n) function:

  • Computes the factorial of n by multiplying the prime factorizations of all integers from 2 to n.
  • For each i in 2 to n:
  • Gets the prime factors using primeFactors(i).
  • Multiplies the result by p ** exponent for all prime factors p.

Time Complexity:

  • primeFactors(i) takes up to O(√i) time.
  • Running it from 2 to n gives:
  • Total time: O(n√n) in the worst case.

Space Complexity:

  • Space for the factors dictionary during each iteration is O(log n) (since the number of distinct prime factors of n is bounded by log n).
  • Total space: O(1) extra (no persistent storage of all factorizations).

7. Using For Loop

The for loop iteratively multiplies numbers in a sequence. Here’s how to calculate the factorial of a number using a for loop:



def factorial_for_loop(n):
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result
           
Read More:

Explanation (No Code):

  • The function calculates the factorial of n using a simple for loop.
  • It initializes a variable result to 1.
  • Iterates from 1 to n (inclusive), multiplying result by each i.
  • After the loop ends, result holds the value of n!.

Time Complexity: O(n)

  • The loop runs n times, performing a constant-time multiplication on each iteration.

Space Complexity: O(1)

  • Only a fixed amount of space is used (result and loop counter i), regardless of the input size.

Comparison Between Different Methods of Finding Factorials

Method NameApproachTime ComplexitySpace Complexity
While Loop (Iterative)Iterative using a while loopO(n)O(1)
Recursive MethodRecursionO(n)O(n)
Built-in (math.factorial)Uses Python standard libraryO(n)*O(1)
NumPy Product MethodNumPy prod() over rangeO(n)O(n)
Prime Factorization MethodMultiply prime factorizationsO(n√n)O(1)
For Loop (Iterative)Iterative using a for loopO(n)O(1)
Summary

In the above tutorial, we explored different ways to compute a factorial in Python. Make sure you're comfortable with basic concepts like loops, recursion, modules, and functions before applying these methods. Enroll in our Python Certification Course to become a full-stack Python developer and secure a high-paying job. Explore our Python career guide to clarify any confusion regarding learning Python.

FAQs

You can code a factorial in Python using recursion, iteration, ternary operator, 
built-In function, numpy.prod, and prime factorization method.

Factorial logic involves multiplying a number by all positive integers less than itself, recursively reducing the problem until reaching the base case of factorial(1) = 1.

The factorial formula in programming is typically expressed as n!=n×(n−1)×(n−2)×…×1, where n is a non-negative integer. It represents the product of all positive integers from 1 to 𝑛, inclusive.

An example of a factorial is 5!, which equals 5×4×3×2×1-=120

Take our Python skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article
About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Live Training - Book Free Demo
Azure AI Engineer Certification Training
17 Jul
07:00AM - 09:00AM IST
Checkmark Icon
Get Job-Ready
Certification
Accept cookies & close this