Python Program - to calculate factorial of a number using while loop
Program to calculate factorial of a number using while loop
Program to calculate factorial of a number using while loop
Here is a Python program to calculate the factorial of a number using a while loop:
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)
Enter a positive integer: 5
The factorial of 5 is 120
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.
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.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.