Factorial in Python: for Loop, Recursion and math.factorial()

The factorial of a nonnegative integer n, written n!, is the product of all positive integers from 1 through n. Thus 5! = 120 and 0! = 1.

Interactive Companion Jupyter Notebook

Run the Python examples, compare expected outputs, modify the code, and complete guided exercises.

View on GitHub Open in Google Colab
On this page — Show page sections— Hide page sections

First working example

n = 6
result = 1
for i in range(1, n + 1):
    result *= i
print("Factorial:", result)

Output:

Factorial: 720

The loop starts with 1 so the same code correctly handles 0!.

Original input-based factorial loop

The original page asks the user to enter the number. Reject negative integers before calculating.

n = int(input("Enter a number: "))
if n < 0:
    print("Factorial is undefined for negative integers")
else:
    total = 1
    for i in range(1, n + 1):
        total *= i
    print("Factorial:", total)

Output:

Factorial: 720

Recursive factorial function

The original recursive code stops only at 1, which does not handle 0. This version has a base case for 0 and 1.

def fact(n):
    if n < 0:
        raise ValueError("n must be nonnegative")
    if n <= 1:
        return 1
    return n * fact(n - 1)

print(fact(4))
print(fact(0))

Output:

24
1

Use math.factorial()

Python has a standard-library function for factorials of nonnegative integers.

from math import factorial
for value in (0, 1, 5, 10):
    print(value, factorial(value))

Output:

0 1
1 1
5 120
10 3628800

Compare loop and recursion

Both compute identical values for small inputs; the loop avoids recursion depth limits.

from math import factorial
def factorial_loop(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result
for n in range(7):
    print(n, factorial_loop(n) == factorial(n))

Output:

0 True
1 True
2 True
3 True
4 True
5 True
6 True

Factorial sequence

Factorials grow quickly: 1, 1, 2, 6, 24 and 120 for 0! to 5!.

from math import factorial
print([factorial(n) for n in range(6)])

Output:

[1, 1, 2, 6, 24, 120]

Validate an invalid value

Negative integers must raise or produce a clear message, not silently return 1.

from math import factorial
try:
    print(factorial(-3))
except ValueError:
    print("Use a nonnegative integer")

Output:

Use a nonnegative integer

Common mistakes and troubleshooting

  • Run each example in Python 3.9 or newer. Indentation is significant in loops and functions.
  • Remember that input() returns a string. Convert and validate the value before doing arithmetic.
  • Check boundary values such as zero, negative numbers, small inputs and empty ranges.
  • When comparing outputs, note whether a code sample uses fixed values or user input.

Practice exercises

Try computing factorials for 0, 1, 6 and 10. Explain why a recursive base case is essential. Use the companion practice notebook for runnable examples and self-checks.

Frequently asked questions

What is 0 factorial?

0! is defined as 1.

Can factorial accept negative numbers?

No. math.factorial() raises ValueError for negative integers.

Should I use recursion for very large n?

Use an iterative algorithm or math.factorial(); recursion has depth limits.

Factorial using recursive function

Plus2Net Python Basics podcast playlist

Other related resources

Back to top ↑




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer