Write Python. Understand every error.

Open the editor

Python programs · Numbers

Python program to find the factorial of a number

The factorial of n, written n!, is 1 × 2 × 3 × … × n. It counts the ways to arrange n different things in a row.

Approach

  1. Start a running product at 1.
  2. Multiply it by every number from 2 to n.
  3. Print the final product.

The program

n = int(input())
result = 1
for i in range(2, n + 1):
    result *= i
print(f"{n}! = {result}")

Sample run

Input
5
Output
5! = 120

Run this program in Py-CRAFT

How the code works

range(2, n + 1) runs from 2 to n, because the stop value is never included. The product starts at 1, not 0, since multiplying by 0 would erase everything. By definition 0! is 1, and this loop gives that answer too: the loop body never runs, so the result stays 1. Python integers grow as large as needed, so large factorials print in full.

Try changing it

Common mistakes

Learn the ideas

More programs

Share this page: