Print the Factorial of a Given Number

Calculate and print the factorial of a number.

BeginnerPhase 2 - Level 1: Basic LoopingExample 4 of 14
print-the-factorial-of-a-given-number.py
1# Take n as input
2n = int(input("Enter n: "))
3
4# Calculate factorial
5factorial = 1
6for i in range(1, n + 1):
7 factorial *= i
8
9print(f"Factorial of {n} is {factorial}")

Output

Enter n: 5
Factorial of 5 is 120

What's going on

Multiply numbers from 1 to n.

Key Concepts:

Initialize factorial to 1
Multiply by each number from 1 to n
5! = 1 * 2 * 3 * 4 * 5 = 120