DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk2 min

Factorial of a Number in Python: Examples, Input Handling, and Recursion

Use Python’s math.factorial() for a nonnegative integer. See working examples, input edge cases, recursion, and when SciPy’s factorial function may fit better.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For the factorial of a nonnegative integer in Python, use math.factorial() from the standard library:

import math

n = 5
print(math.factorial(n))  # 120

A factorial multiplies an integer by every positive integer below it: n! = n × (n − 1) × … × 1. By definition, 0! is 1. Python’s documentation describes math.factorial(n) as returning the factorial of the nonnegative integer n (Python 3.14.7 math documentation).

What the factorial function returns

For example, 5! = 5 × 4 × 3 × 2 × 1 = 120. The first values include 0! = 1, 1! = 1, and 5! = 120. The zero case is a mathematical definition, not an error or an empty result (OpenStax, Introduction to Python Programming).

Read a number and handle invalid input

input() returns text, so convert it to an integer before calling math.factorial(). This example reports text that cannot be parsed as an integer and rejects negative integers with a clear message:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import math

try:
    n = int(input("Enter a nonnegative integer: "))
    if n < 0:
        raise ValueError("n must be nonnegative")
    print(math.factorial(n))
except ValueError as error:
    print(f"Invalid input: {error}")

math.factorial() raises ValueError for negative or non-integral inputs, according to the Python 3.12 math documentation. With the conversion above, inputs such as 3.5 are rejected by int(); a decimal string is not silently treated as a factorial input.

Inputs that need special attention

  • Zero: math.factorial(0) returns 1.
  • Negative integers: They are outside the function’s supported domain; Python raises ValueError.
  • Non-integral numbers: They are not factorial inputs for math.factorial() and raise ValueError.
  • Integral-valued floats: Do not pass 5.0. Python deprecated accepting such values in 3.9 and stopped accepting them in 3.10; pass the integer 5 instead (Python math documentation).

Python integers can represent results beyond a fixed machine-width integer range, but factorial results grow quickly, so calculation time and the number of digits in the output increase with the input. No universal practical cutoff follows from the API documentation.

When to write a recursive version

Recursion is useful when the goal is to learn how a problem can be defined in terms of a smaller version of itself. The recurrence is n! = n × (n − 1)!, with 0! and 1! as stopping cases (OpenStax):

def factorial_recursive(n):
    if n < 0:
        raise ValueError("n must be nonnegative")
    if n in (0, 1):
        return 1
    return n * factorial_recursive(n - 1)

Each call reduces the argument by one until it reaches a base case. Without that stopping case, the function would keep calling itself. Each recursive level also uses a call frame, so for ordinary application code the standard-library function is the simpler choice; use recursion when its teaching value is the point.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should you use SciPy instead?

For one scalar factorial in ordinary Python, use math.factorial(). SciPy’s scipy.special.factorial is an alternative for scientific workflows, including array inputs, but it has different options and behavior (SciPy reference).

Function Typical fit Result and negative inputs
math.factorial(n) Scalar nonnegative integer in standard Python Exact integer result; negative input raises ValueError.
scipy.special.factorial(n) Scientific or array-oriented calculations The exact option selects exact integer calculation or a faster floating-point approximation; the documented default for negative values is zero.

These functions are not interchangeable at the edges: in particular, SciPy’s documented negative-input default does not match the standard library’s exception behavior.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common confusion: factorial of a number or of its digits?

math.factorial(123) computes 123!, the factorial of the whole integer. It does not compute 1! + 2! + 3! or the factorial of each digit separately. Those are different operations and need a separately specified rule for combining the digit results.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.