Find Factorial in Python

Beginner
⏱️ 8 min read
📚 Updated: May 2026
🎯 2 Code Examples
Recursion & loop

What you’ll learn

  • The definition of n! for n ≥ 0, including 0! = 1.
  • A recursive solution matching classic interview style, plus an iterative equivalent.
  • Input validation, recursion-depth limits, and a small live preview.

Overview

Factorial grows very fast. A correct small-n program is easy; a robust one also checks n ≥ 0, explains recursion limits, and offers an iterative fallback.

Two programs

Recursive and iterative Python versions, both producing the same answer.

Live preview

Interactive check for exact values in JavaScript safe integer range.

Rigor

Validates negatives and explains recursion-depth concern for large n.

Prerequisites

Functions, if, multiplication, and basic for loops.

  • def functions, return, and formatted output with print().
  • Awareness that recursion in Python has a depth limit; loops are safer for very large n.

What is factorial?

For an integer n ≥ 0, n! is the product of every integer from 1 through n. When n = 0, that is the empty product, defined as 1.

Factorials count permutations: n! is the number of ways to order n distinct objects.

5! 120
Recurrence n! = n·(n-1)!
0! 1

Formal definition

Define 0! = 1 and, for n ≥ 1, n! = n · (n-1)!. Equivalently n! = ∏k=1n k.

5!

5 × 4 × 3 × 2 × 1 = 120.

Intuition

5! 120
Expand
5·4·3·2·1
6! 720
Step
6 · 5!

Takeaway: each increment of n multiplies the previous factorial by n, which is why values explode in size.

Live preview

Exact factorial for 0 ≤ n ≤ 20 (easy to verify and safe to display exactly in JavaScript).

Try 0, 12, or 20. Values above 20 are blocked in this widget.

Live result
Press “Compute n!”.

Algorithm

Goal: compute n! for nonnegative n.

Base case

If n ≤ 1, return 1 (covers 0! and 1!).

Recurrence or loop

Otherwise compute n * factorial(n-1), or iteratively multiply factors from 2 to n.

📜 Pseudocode

Pseudocode
function factorial(n):  // assume n >= 0
    if n <= 1:
        return 1
    return n * factorial(n - 1)
1

Recursive factorial

Classic recursive style with input validation, suitable for interview explanation of base case + recurrence.

python
def factorial_recursive(n: int) -> int:
    if n < 0:
        raise ValueError("Factorial is not defined for negative integers.")
    if n <= 1:
        return 1
    return n * factorial_recursive(n - 1)

number = 5
result = factorial_recursive(number)
print(f"Factorial of {number} is: {result}")

Explanation

Each call reduces n until base case 1, then products are built while returning.

2

Iterative factorial

Same numeric result for n = 5, with O(1) auxiliary space and no recursion-depth risk.

python
def factorial_iterative(n: int) -> int:
    if n < 0:
        raise ValueError("Factorial is not defined for negative integers.")

    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

number = 5
print(f"Factorial of {number} is: {factorial_iterative(number)}")

Explanation

The loop multiplies 1 by every integer from 2 to n. For n in {0, 1}, result stays 1.

Optimization and scaling

Built-in option. Python provides math.factorial(n), optimized and battle-tested for integer inputs.

Large n strategy. Prefer loops or math.factorial over recursion to avoid recursion-depth exceptions.

Interview: explain base case, time complexity, and recursion-depth tradeoff.

❓ FAQ

For a nonnegative integer n, n! is the product of all integers from 1 through n. By definition, 0! = 1.
Both 0! and 1! equal 1. Those cases terminate the recurrence n! = n * (n-1)!.
Python integers are arbitrary precision, so they grow as needed. You usually hit time or memory limits before integer overflow.
Both run O(n) multiplications. Recursion uses O(n) call stack space and can hit recursion-depth limits; a loop uses O(1) extra space.
Factorial is not defined for negative integers in the standard combinatorial sense. Validate n >= 0 before computing.
Computing n! with n multiplications costs O(n) time. Space is O(n) for recursion depth or O(1) for iterative loop, excluding result size.

🔄 Input / output examples

Try these values with either Python example:

nn!
01
11
5120
202432902008176640000

Edge cases and pitfalls

Python integers grow automatically, but recursion depth and runtime still matter.

Negative

n < 0

Not defined in standard factorial; reject with clear error.

Recursion

Deep recursion

Large n can raise RecursionError; iterative code avoids this.

Huge output

Very large factorials

Numbers can be exact but enormous; printing and memory become expensive.

Validation

Non-integer input

Accept only integers for this interview problem to keep definition precise.

⏱️ Time and space complexity

VersionTimeExtra space
RecursiveO(n) multiplicationsO(n) call frames
IterativeO(n) multiplicationsO(1)

Both approaches use Θ(n) arithmetic operations for exact n!; stack usage is the key difference.

Summary

  • Definition: 0! = 1 and n! = n·(n-1)! for n ≥ 1.
  • Code: recursion matches theory; iteration avoids recursion-depth limits.
  • Watch-outs: validate negatives and explain why loops are safer for very large n.
Did you know?

Stirling's approximation is often used to estimate how fast n! grows: n! ∼ √(2πn) · (n/e)n.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful