Calculate Factorial (Loop) in Python

Calculate the factorial of a non-negative integer using a loop.

BeginnerLoop ProgramsExample 6 of 25
calculate-factorial-loop.py
Run in browser
1# Program to calculate factorial using a loop
2
3n = int(input("Enter a non-negative integer: "))
4
5if n < 0:
6 print("Factorial is not defined for negative numbers.")
7else:
8 fact = 1
9 for i in range(1, n + 1):
10 fact *= i
11 print(f"Factorial of {n} is {fact}")

Output

Enter a non-negative integer: 5
Factorial of 5 is 120

What's going on

We multiply numbers from 1 to n in a loop to compute n! (factorial).