Find Factorial in Python

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Recursion & loop

What You’ll Learn

Factorial n! is the product of integers from 1 through n, with 0! = 1. This tutorial covers recursive and iterative solutions, math.factorial, a live preview, worked Python examples, edge cases, and complexity.

Definition

n! & 0!

Product 1…n; empty product gives 0! = 1.

Recurrence

n·(n-1)!

Classic recursive interview form.

Iterative

O(1) space

Loop multiply avoids recursion-depth limits.

math.factorial

Builtin

Best for real code after you can write it yourself.

Live Preview

n ≤ 20

Exact factorials in the browser for small n.

O(n)

Multiplies

Both styles use Θ(n) multiplications.

Introduction

Factorial for an integer n ≥ 0 is the product of every integer from 1 through n. By definition, 0! = 1 (the empty product). Example: 5! = 5 × 4 × 3 × 2 × 1 = 120.

Factorials count permutations: n! is the number of ways to order n distinct objects. Values grow extremely fast — a correct small-n program is easy; a robust one also validates n ≥ 0 and prefers loops for large n.

Why it matters?

It is the classic interview problem for base cases, recurrence vs loops, and recursion-depth tradeoffs.

Key Highlights

0! = 1

Empty product — say it clearly in interviews.

Recurrence

n! = n · (n-1)! for n ≥ 1.

Loop Safer

Iteration avoids recursion-depth errors.

No Negatives

Reject n < 0 — factorial is undefined there.

In short: for n ≥ 0, multiply 1 through n (or return 1 when n is 0 or 1).

📝 Problem & Approach

Given a nonnegative integer n, compute n!.

python
# 0! = 1
# 5! = 5 * 4 * 3 * 2 * 1 = 120
# 6! = 6 * 5! = 720

Inputs & Outputs

ItemTypeDescription
nintNonnegative integer (reject negatives).
Return / printint / textExact value of n!.

Minimal workflow

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

Method comparison

MethodIdeaNotes
Recursiven * factorial(n-1)Matches theory; O(n) stack
IterativeMultiply 2…n in a loopO(1) extra space
math.factorialBuiltinBest for production code

⚡ Quick Reference

GoalPattern
Base caseif n <= 1: return 1
Recurrencereturn n * factorial(n - 1)
Loopfor i in range(2, n + 1): result *= i
Builtinmath.factorial(n)
Classic values0! = 1, 5! = 120, 10! = 3628800
Rejectn < 0 → raise / error

📋 Recursive vs Iterative vs Builtin

Three ways to compute n! — pick by clarity and constraints.

Recursive
n * f(n-1)

Teaches base case + recurrence

Iterative
loop *= i

Safer for large n (no stack depth)

Builtin
math.factorial

Optimized and battle-tested

Interview tip
both + tradeoff

Show recursion, then mention loop

Context

When This Problem Shows Up

Reach for factorial when products, permutations, or recursion drills appear.

  1. Interview warm-ups

    First recursion problem many candidates see.

  2. Combinatorics

    Permutations and combinations use n!.

  3. Teaching recursion

    Clear base case and single recursive call.

  4. Before Fibonacci

    Natural precursor to recursive sequences.

  5. Not for negatives

    Validate n ≥ 0 before computing.

Key benefit: one short function that forces clear thinking about base cases, space, and growth.

🔮 Live Preview

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

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

Live result
Press “Compute n!”.

Examples Gallery

Three complete Python programs — recursive, iterative, and math.factorial. Click View Output to reveal sample console results.

📚 Getting Started

Base case + recurrence for interview explanations.

Example 1 — Recursive Factorial

Classic recursive style with input validation.

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}")

How It Works

Each call reduces n until the base case 1, then products are built while returning. Stack depth is O(n), so large n can raise RecursionError.

⚡ Iterative Style

Same numeric result with O(1) auxiliary space.

Example 2 — Iterative Factorial

No recursion-depth risk; multiply factors from 2 to n.

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)}")

How It Works

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

⚙️ Builtin Style

Use the standard library when you do not need to reinvent the wheel.

Example 3 — math.factorial

Optimized and battle-tested for integer inputs.

python
import math

for n in (0, 1, 5, 10, 20):
    print(f"{n}! = {math.factorial(n)}")

How It Works

Prefer math.factorial in real projects. In interviews, write recursive or iterative yourself first, then mention the builtin.

🧠 How the Algorithm Computes

1

Validate

Reject n < 0; factorial is not defined for negatives.

Guard
2

Base case

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

Stop
3

Recurrence or loop

Compute n * factorial(n-1), or multiply 2…n.

Product
=

n!

Exact product for nonnegative n.

🔎 Worked Walkthrough — n = 5

Trace the recursive expansion for the classic interview value.

CallExpressionReturns
f(5)5 * f(4)waits
f(4)4 * f(3)waits
f(3)3 * f(2)waits
f(2)2 * f(1)waits
f(1)base1
unwind2*1 … 5*24120

Final answer: 5! = 120.

Use Cases

Where factorial shows up beyond the interview prompt.

1. Interview Warm-Ups

Base case, recurrence, and loop tradeoffs.

Example: write factorial(n).

2. Permutations

n! counts orderings of n items.

Example: 5 books → 120 orders.

3. Combinations

C(n, k) uses factorials in the formula.

Example: n! / (k!(n-k)!).

4. Teaching Recursion

Single recursive call with a clear stop.

Example: chalkboard unwind of 5!.

5. Before Fibonacci

Warm-up for recursive series problems.

Example: next page in this chain.

6. Growth Awareness

Stirling’s approximation for large-n intuition.

Example: estimate digit growth of n!.

Pro Tip: say “0! = 1” before coding — interviewers listen for that base case.

Advantages

Why this pattern works well in interviews and classwork.

  1. 1. Clear Math

    One recurrence and one base case tell the whole story.

  2. 2. Two Valid Styles

    Recursion matches theory; loops scale better.

  3. 3. Famous Test Cases

    0, 1, 5, and 20 are easy to verify.

  4. 4. Builtin Escape Hatch

    math.factorial is ready for production use.

Pro Tip: show recursion for the whiteboard, then say you would ship the iterative or builtin version.

Usage Tips

Small habits that keep factorial solutions interview-ready.

  1. 1. State 0! = 1

    Call out the empty-product base case first.

  2. 2. Validate Negatives

    Raise a clear error for n < 0.

  3. 3. Prefer Loops for Large n

    Avoid recursion-depth exceptions.

  4. 4. Mention math.factorial

    Show you know the production shortcut.

  5. 5. Spot-Check 5 and 0

    120 and 1 catch base-case mistakes fast.

Pro Tip: Python ints do not overflow like C — talk about time/memory instead of fixed-width overflow.

Common Pitfalls

Mistakes that commonly break factorial solutions.

  1. 1. Forgetting 0!

    Returning 0 or raising for n = 0.

    → Base case: n ≤ 1 returns 1.

  2. 2. Accepting Negatives Silently

    Recursive calls never hit a base case for n < 0.

    → Validate and raise early.

  3. 3. Deep Recursion Only

    Large n hits RecursionError.

    → Prefer iterative or math.factorial for big n.

  4. 4. Off-by-One in the Loop

    Using range(2, n) drops the last factor.

    → Use range(2, n + 1).

  5. 5. Worrying About C-style Overflow

    Python ints grow; talk about time/memory instead.

    → Mention arbitrary-precision integers explicitly.

Edge Cases

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

Negative

n < 0

Not defined in standard factorial; reject with a clear error.

Zero / one

0! and 1!

Both equal 1 — your base case must cover them.

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.

Loop bound

range(2, n + 1)

Inclusive end so the last factor is included.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Formal. 0! = 1 and n! = n · (n-1)! for n ≥ 1; equivalently ∏k=1n k.
  • Permutations. n! counts ways to order n distinct objects.
  • Growth. Each step multiplies by n, so values explode quickly.
  • Stirling. Approximate growth with √(2πn) · (n/e)n.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Verify classics

  • 0! = 1, 5! = 120
  • 10! = 3628800

2. Match both styles

  • Recursive vs iterative
  • Assert identical results

3. Reject negatives

  • Raise ValueError for n < 0
  • Write a short unit test

4. Print the expansion

  • Show 5 * 4 * 3 * 2 * 1
  • Then the final value

Notes

  • Definition: 0! = 1 and n! = n·(n-1)! for n ≥ 1.
  • Code: recursion matches theory; iteration avoids recursion-depth limits.
  • Watch-outs: validate negatives; prefer loops for very large n.
  • Both styles use Θ(n) multiplications; stack usage is the key difference.

Quick Takeaway: multiply 1 through n (with 0! = 1); use recursion to explain, loops (or math.factorial) to ship.

⏱️ Time and Space Complexity

VersionTimeExtra space
RecursiveO(n) multiplicationsO(n) call frames
IterativeO(n) multiplicationsO(1)
math.factorialO(n) (implementation detail)O(1) beyond result size

Both approaches use Θ(n) arithmetic operations for exact n!; stack usage is the key difference. Result size grows with n and is excluded from the “extra space” column above.

Wrap Up

🎉 Conclusion

Factorial multiplies 1 through n, with 0! = 1 by definition. Use recursion to match the recurrence, prefer an iterative loop (or math.factorial) when n grows, and always reject negatives.

Practice the three examples above, then continue to Fibonacci for the next classic sequence problem.

State the base case, explain O(n) time, and call out recursion-depth vs O(1) loop space.

💡 Best Practices

✅ Do

  • State 0! = 1 up front
  • Validate n ≥ 0
  • Show recursive and iterative
  • Prefer loops for large n
  • Mention math.factorial

❌ Don’t

  • Return 0 for 0!
  • Recurse on negatives
  • Ignore recursion-depth limits
  • Use range(2, n) by mistake
  • Assume C-style int overflow

Key Takeaways

Knowledge Unlocked

Five things to remember about factorial

Compute n! the interview-friendly way.

5
Core concepts
r 02

Recur

n·(n-1)!

Theory
i 03

Iterate

O(1) space

Practice
- 04

Guard

n ≥ 0

Edge
O 05

Cost

Θ(n) ×

Analysis

❓ Frequently Asked Questions

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.
Yes for real code. In interviews, write recursive or iterative yourself, then mention the builtin.
It is the empty product, and it makes the recurrence n! = n*(n-1)! work for n = 1.

Did you Know? 🔊

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

Continue to Fibonacci Series

Learn iterative and recursive ways to print the Fibonacci sequence.

Fibonacci tutorial →

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.

9 people found this page helpful