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 understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.