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.
Run the Python examples, compare expected outputs, modify the code, and complete guided exercises.
View on GitHubn = 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!.
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
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
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
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
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]
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
input() returns a string. Convert and validate the value before doing arithmetic.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.
0! is defined as 1.
No. math.factorial() raises ValueError for negative integers.
Use an iterative algorithm or math.factorial(); recursion has depth limits.

Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.