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 browser1# Program to calculate factorial using a loop23n = int(input("Enter a non-negative integer: "))45if n < 0:6 print("Factorial is not defined for negative numbers.")7else:8 fact = 19 for i in range(1, n + 1):10 fact *= i11 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).