Calculate Factorial (Loop)

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

BeginnerTopic: Loop Programs
Back

Python Calculate Factorial (Loop) Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# 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

Understanding Calculate Factorial (Loop)

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

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.

Table of Contents