Calculate Factorial (Loop)

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

PythonBeginner
Python
# Program to calculate factorial using a loop

n = int(input("Enter a non-negative integer: "))

if n < 0:
    print("Factorial is not defined for negative numbers.")
else:
    fact = 1
    for i in range(1, n + 1):
        fact *= i
    print(f"Factorial of {n} is {fact}")

Output

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

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