Home › Python programs

Factorial Program in Python

Problem statement

Calculate n! by multiplying every integer from 1 through n. Handle zero correctly: 0! is 1.

Approach 1: simple loop

Start with the clearest algorithm. Read the input, initialise the answer, and use a for or while loop to process one small piece at a time.

n = 5
answer = 1
for value in range(1, n + 1):
    answer = answer * value
print(answer)
# Output: 120

This version is deliberately explicit: every update is visible, which makes it useful while learning and while debugging a wrong output.

Approach 2: reusable function

Put the logic in a function so it can be tested with several inputs. A function also makes the boundary rules obvious and keeps input/output separate from computation.

def solve(n):
    result = 1
    for value in range(1, n + 1):
        result *= value
    return result

print(solve(5))
# Output: 120

Test normal values, the smallest valid value, and an invalid value. Returning a value is easier to reuse than printing inside the algorithm.

Approach 3: Pythonic alternative

Python often has a compact alternative, but use it only after understanding the loop. For example, a built-in, a generator expression, or tuple unpacking can reduce bookkeeping. Keep the compact form readable and explain its assumptions.

# Compact style: the operation is still the same idea
values = [1, 2, 3, 4, 5]
result = 1
for value in values:
    result *= value
print(result)
# Output: 120

Compare outputs between implementations. If they disagree, inspect the intermediate values instead of guessing.

Dry run

For input 5, write a small trace table: before the first iteration the answer is 1; after processing 1, 2, 3, 4 and 5 it becomes 1, 2, 6, 24 and 120. The loop stops exactly at the intended boundary. For a different problem, apply the same method: record the current digit, update the accumulator, then record the new state. This turns an abstract loop into a sequence of verifiable steps.

Common errors

Practice on PyDebug

Turn the idea into a debugging habit with these free browser exercises: