Beginner Number Problems Python

Factorial Program in Python with Output

Compute n! for a non-negative integer n in Python using a loop and using recursion.

  • TimeO(n) multiplications for both versions
  • SpaceO(1) for the loop, O(n) call stack for recursion
  • Hints3
  • Read3 min
Quick answer

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).

for and while loopsRecursionBase casePython big integers
1

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.

Input

A non-negative integer n.

Output

The value of n!.

Examples

Example 1
Inputn = 5
Output120

1 x 2 x 3 x 4 x 5 = 120.

Example 2
Inputn = 0
Output1

0! is defined as 1, the empty product.

Example 3
Inputn = 10
Output3628800

The 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
2

Think before you code

Reveal the questions to ask yourself first
  • What should result start at: 0 or 1? What happens if you start at 0?
  • How is 5! related to 4!?
  • Where must a recursive function stop?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Start with result = 1 and multiply, never add.
2 Hint 2
range(2, n + 1) includes n. range(2, n) would miss the last multiplication.
3 Hint 3
For recursion, the base case is n <= 1, which returns 1. That covers both 0! and 1!.
4

Approach

Reveal the step-by-step approach

Factorial using loop in Python

  1. Set result = 1.
  2. For every i from 2 to n, do result = result * i.
  3. Return result. For n = 0 or n = 1 the 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
5

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
6

Solution

Reveal the full Python solution
solution.py
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.

TimeO(n) multiplications for both versions
SpaceO(1) for the loop, O(n) call stack for recursion
7

Review 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

Practising Python for interviews?

CodeBegun’s Python Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us