Home / Programs / Python Program - to calculate factorial of a number using while loop
Programming Example

Python Program - to calculate factorial of a number using while loop

👁 291 Views
💻 Practical Program
📘 Step by Step Learning

Program to calculate factorial of a number using while loop

Information & Algorithm

Here is a Python program to calculate the factorial of a number using a while loop:

Program Code

num = int(input("Enter a positive integer: "))
factorial = 1
i = 1

while i <= num:
    factorial *= i
    i += 1

print("The factorial of", num, "is", factorial)

Output

Enter a positive integer: 5
The factorial of 5 is 120

Explanation

In this program, we prompt the user to enter a positive integer using the input() function and convert it to an integer using the int() function. We initialize two variables: factorial, which will store the factorial of the number, and i, which we will use to iterate over the numbers from 1 to num.

We use a while loop to iterate over the numbers from 1 to num. In each iteration of the loop, we multiply factorial by i and increment i by 1. This calculates the product of all the numbers from 1 to num, which is the factorial of num.

Finally, we print out the result using the print() function.

This program demonstrates the sequential flow of execution in Python, where the statements are executed in the order in which they appear in the code. The while loop causes the statements inside the loop (i.e., the repeated multiplication of factorial by i and the incrementation of i) to be executed until the condition i <= num becomes False, resulting in the final value of factorial.

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.