Python Practice › Basic Programs › Program 23

Factorial of a number

EasyBasic Programs · 23 of 40

Write a Python program to find the factorial of a number. n! = 1 × 2 × … × n, and 0! = 1.

Advertisement
Input
n = 6
Output
6! = 720

Approach

  1. Start with 1 and multiply by every number from 2 to n.

Solution 1: loop

Python
n = 6factorial = 1for i in range(2, n + 1):    factorial *= iprint(f"{n}! = {factorial}")
Output
6! = 720

Line by line

Line 2

Start at 1, the identity for multiplication (and the value of 0!).

Line 3

range(2, n + 1) gives 2, 3, 4, 5, 6; the end value is excluded, so add 1.

Line 4

*= multiplies the running result by each number.

Solution 2: math.factorial

Python
import mathprint(math.factorial(6), math.factorial(0))
Output
720 1

Line by line

Line 2

The standard library already has an efficient factorial function.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs