PythonMastery

Factorial program in Python

Calculate the factorial of a number with a for loop, check for negative input, and compare the result with math.factorial().

The factorial of a whole number n, written n!, is the product of all whole numbers from 1 to n. For example, 5! = 1 × 2 × 3 × 4 × 5 = 120. By definition, 0! is 1.

The program

python
n = int(input("Enter a whole number: "))

if n < 0:
    print("Factorial is not defined for negative numbers.")
else:
    result = 1
    for i in range(1, n + 1):
        result *= i
    print(f"{n}! = {result}")

Typed in this example: 6. Press Run to type your own.

output
Enter a whole number: 6
6! = 720

How it works

Another way: math.factorial()

The math module has a built-in function for this:

python
import math

print(math.factorial(6))
print(math.factorial(20))
output
720
2432902008176640000

math.factorial() raises a ValueError for negative numbers. The same calculation written as a function that calls itself is on the factorial using recursion page.

Learn the idea: Loops: for, while, and the Pythonic Patterns, Input & Output: Talking to Your User