Skip to main content

Learning outcomes

By the end of this lecture, you should be able to:
  • define factorial mathematically
  • implement factorial using while
  • trace factorial loops for any n
  • handle edge cases (0, negative input)

Factorial definition

  • n! = n * (n-1) * (n-2) * ... * 1
  • 0! = 1
Examples:
  • 5! = 120
  • 3! = 6

Standard while solution

n = int(input("Enter n: "))

if n < 0:
    print("Factorial not defined for negatives")
else:
    fact = 1
    i = 1
    while i <= n:
        fact *= i
        i += 1
    print(fact)

Why initialize fact = 1

  • multiplicative identity is 1
  • starting at 0 would make final answer always 0

Dry run for n = 5

Iterationifact beforefact *= ifact after
1111 * 11
2211 * 22
3322 * 36
4466 * 424
552424 * 5120

Compact variant

n = int(input())
fact, i = 1, 1
while i <= n:
    fact *= i
    i += 1
print(fact)

Common mistakes

  • fact = 0 (wrong start)
  • while i < n (misses multiplying by n)
  • forgetting i += 1
  • not handling negative n

Exam hints and traps

  • always remember 0! = 1
  • for n = 1, output is 1
  • negative inputs are invalid for standard factorial

Practice

  1. Write factorial using descending loop (i = n down to 1).
  2. Predict output for n = 0.
  3. Fix bug:
n = 4
fact = 1
i = 1
while i < n:
    fact *= i
    i += 1
print(fact)

Answer key

fact = 1
i = n
while i >= 1:
    fact *= i
    i -= 1
  1. 1
  2. condition should be while i <= n: