Python Program - to calculate factorial of a number using while loop
Python Loop control in Python (Article) Loop control in Python (Program)
141
Here is a Python program to calculate the factorial of a number using a while
loop:
Program:
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
.
This Particular section is dedicated to Programs only. If you want learn more about Python. Then you can visit below links to get more depth on this subject.