Factorial Program in Python with Output
Compute n! for a non-negative integer n in Python using a loop and using recursion.
- Time
O(n) multiplications for both versions - Space
O(1) for the loop, O(n) call stack for recursion - Hints3
- Read3 min
The factorial of n, written n!, is the product 1 x 2 x 3 x ... x n, and 0! is 1. In Python, start with result = 1 and multiply it by every i in range(2, n + 1). The recursive version is factorial(n) = n * factorial(n - 1) with factorial(0) = factorial(1) = 1. Python integers do not overflow, so even 25! prints exactly. The standard library also has math.factorial(n).
Problem statement
Write a factorial program in Python. Given a non-negative integer n, print n!.
Write it twice: once with a loop and once with recursion. For example, 5! = 5 x 4 x 3 x 2 x 1 = 120.
A non-negative integer n.
The value of n!.
Examples
n = 51201 x 2 x 3 x 4 x 5 = 120.
n = 010! is defined as 1, the empty product.
n = 103628800The product of 1 to 10.
Constraints
- n >= 0. Factorial is not defined for negative numbers
- The recursive version fails for n near 1000 because of Python's default recursion limit
Think before you code
Reveal the questions to ask yourself first
- What should
resultstart at: 0 or 1? What happens if you start at 0? - How is
5!related to4!? - Where must a recursive function stop?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
Factorial using loop in Python
- Set
result = 1. - For every
ifrom 2 ton, doresult = result * i. - Return
result. Forn = 0orn = 1the loop does not run, and 1 is returned.
Factorial using recursion in Python
n! = n x (n - 1)!. So the function calls itself with n - 1 until it reaches the
base case:
factorial(n) = 1 if n <= 1
factorial(n) = n * factorial(n - 1) otherwise
See what is recursion for how the calls wait on each other.
| Version | Time | Extra space | Limit in Python |
|---|---|---|---|
| Loop | O(n) | O(1) | None in practice |
| Recursion | O(n) | O(n) call stack | About 1000 calls by default |
math.factorial |
O(n) or better | Handled for you | None in practice |
Dry run
Walk through the example step by step
Loop version, n = 5:
i | result before | result = result * i
--+---------------+--------------------
2 | 1 | 2
3 | 2 | 6
4 | 6 | 24
5 | 24 | 120
Recursive version, factorial(4):
factorial(4) = 4 * factorial(3)
= 4 * (3 * factorial(2))
= 4 * (3 * (2 * factorial(1)))
= 4 * (3 * (2 * 1))
= 24
Solution
Reveal the full Python solution
def factorial_loop(n):
result = 1
for i in range(2, n + 1):
result = result * i
return result
def factorial_recursive(n):
if n <= 1:
return 1
return n * factorial_recursive(n - 1)
for n in [0, 1, 5, 10]:
print(f"{n}! = {factorial_loop(n)} (loop), {factorial_recursive(n)} (recursion)")Output:
0! = 1 (loop), 1 (recursion)
1! = 1 (loop), 1 (recursion)
5! = 120 (loop), 120 (recursion)
10! = 3628800 (loop), 3628800 (recursion)
Both functions give the same answers. The loop keeps one running product. The recursive function builds a chain of calls and multiplies on the way back.
Python factorial code with a while loop and user input
n = int(input("Enter a number: "))
if n < 0:
print("Factorial is not defined for negative numbers")
else:
fact = 1
i = 1
while i <= n:
fact = fact * i
i += 1
print("Factorial of", n, "is", fact)
Enter a number: 6
Factorial of 6 is 720
Enter a number: -3
Factorial is not defined for negative numbers
math.factorial() and big numbers
import math
print(math.factorial(6))
print(math.factorial(25))
720
15511210043330985984000000
Python integers grow as large as needed, so 25! prints exactly. In C or Java an int
overflows after 12!, and a 64-bit long after 20!. In an exam or interview, write the
loop yourself first, then mention math.factorial as the library way.
The recursion depth limit
Python allows about 1000 nested calls by default. A very deep recursive factorial fails:
def factorial_recursive(n):
if n <= 1:
return 1
return n * factorial_recursive(n - 1)
try:
factorial_recursive(5000)
except RecursionError as e:
print("RecursionError:", e)
RecursionError: maximum recursion depth exceeded
The loop version has no such limit, which is why it is the better choice for large n
in Python.
The same problem in Java is on find the factorial of a number using a loop and find the factorial of a number using recursion. Another loop-and-recursion pair is the Fibonacci series program in Python.
O(n) multiplications for both versionsO(1) for the loop, O(n) call stack for recursionReview before the interview
Common mistakes
- Starting result at 0. Anything multiplied by 0 stays 0, so every answer becomes 0.
- Using range(1, n) instead of range(1, n + 1). The last number n is never multiplied in.
- Writing the recursive function without a base case. It calls itself until Python raises RecursionError.
- Forgetting return before n * factorial(n - 1). The function then returns None and the multiplication fails.
Edge cases to test
- 0! = 1 and 1! = 1. Both versions return 1 without entering the loop or recursing.
- Negative input: factorial is undefined. Print a message, as in the input version.
- Large n with recursion: around 1000 and above raises RecursionError. Use the loop.
Interview follow-ups
- How many trailing zeros does 100! have, and how can you count them without computing 100!?
- How would you print the factorials of all numbers from 1 to 10?
- How would you write the recursive version so it never goes below 0?
Keep practising
Find the Factorial of a Number Using a Loop
Hints · Dry run · SolutionSolve Similar problemFind the Factorial of a Number Using Recursion
Hints · Dry run · SolutionSolve Similar problemCheck Whether a Number Is a Strong Number
Hints · Dry run · SolutionSolve Similar problemFind the Nth Fibonacci Number Using Recursion
Hints · Dry run · SolutionSolve Related learningWhat Is Recursion
TutorialLearn Related learningLoops In Programming
TutorialLearn Related learningPython Interview Questions
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising Python for interviews?
CodeBegun’s Python Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
