Python Program to Find Factorial of a Number Using for Loop

1. Introduction

The factorial of a number is a common mathematical function with importance in areas such as combinatorics, algebra, and analysis. In programming, calculating the factorial of a number is often used as an introduction to the concept of loops. In Python, a for loop provides a clear and concise way to compute factorials.

The factorial of a non-negative integer n is denoted by n! and is the product of all positive integers less than or equal to n. The factorial of zero 0! is defined as 1.

2. Program Steps

1. Define the number to calculate the factorial of.

2. Initialize a variable to store the factorial result, starting at 1.

3. Use a for loop to iterate from 1 to the number, inclusive.

4. Multiply the current value of the factorial result by the loop variable in each iteration.

5. Print the factorial result after the loop concludes.

3. Code Program

# Function to calculate factorial using a for loop
def factorial(number):
    result = 1
    # Loop over the range from 1 to number (inclusive)
    for i in range(1, number + 1):
        # Multiply result by current number
        result *= i
    return result

# Number to calculate the factorial of
num = 5
# Calculate factorial
factorial_result = factorial(num)
# Print the result
print(f"The factorial of {num} is: {factorial_result}")


The factorial of 5 is: 120


1. A function named factorial is defined, taking number as its parameter.

2. The variable result is initialized to 1, which will accumulate the product of numbers from 1 to number.

3. The for loop iterates over a range created by range(1, number + 1), which includes number itself.

4. Each iteration multiplies result by the loop variable i, which represents the current number in the sequence.

5. Once the loop is complete, result contains the factorial of number.

6. The factorial function is called with num set to 5 and the result, 120, is printed, indicating that 5! equals 120.

7. The print statement outputs the result in a formatted string using an f-string.