Python Program to Find Factorial of a Number Using While Loop

1. Introduction

Calculating the factorial of a number is a fundamental problem in both mathematics and computer science. In programming, factorials can be calculated using various methods, and here we will focus on using a while loop in Python.

The factorial of a non-negative integer n is the product of all positive integers less than or equal to n, commonly denoted as n!. For example, 5! (5 factorial) is 5 x 4 x 3 x 2 x 1 = 120.

2. Program Steps

1. Start with the number to find the factorial of.

2. Initialize the result as 1.

3. Use a while loop to multiply the result by the number and decrement the number by 1 each iteration.

4. Continue the loop until the number is reduced to 1.

5. Print the final result, which is the factorial of the starting number.

3. Code Program

# Function to calculate the factorial of a number using a while loop
def factorial_with_while(number):
    # Start with the result equal to 1
    result = 1
    # Loop until the number is reduced to 1
    while number > 1:
        # Multiply the result by the current number
        result *= number
        # Decrement the number by 1
        number -= 1
    # Return the factorial
    return result

# Number to calculate the factorial of
num = 5
# Call the function and print the result
factorial_result = factorial_with_while(num)
print(f"The factorial of {num} is: {factorial_result}")

Output:

The factorial of 5 is: 120

Explanation:

1. factorial_with_while is defined to calculate the factorial of number.

2. result is initialized to 1 and will store the intermediate results as the calculation proceeds.

3. A while loop continues to execute as long as number is greater than 1.

4. Within the loop, result is updated to result * number, which accumulates the product of numbers counting down from the starting number.

5. After each multiplication, number is decremented by 1 to proceed to the next lower integer.

6. When number reaches 1, the loop exits, and result now contains the factorial of the original number.

7. The function is used to find the factorial of 5, and the print function displays the result as 120.

8. The output correctly identifies the factorial of 5 as 120.

Comments