Find Factorial of any Number Using While Loop in Python

Here is code to find the factorial of a given number using a while loop in Python:

Simple code:

num = int(input("Enter a number: "))
fact = 1
while num > 0:
    fact *= num
    num -= 1
print("Factorial =", fact)

Output:

Enter a number: 5
Factorial = 120

Code with comments:

# get the input number from the user
num = int(input("Enter a number: "))

# initialize the factorial variable to 1
fact = 1

# continue looping until the input number becomes 0
while num > 0:
    # multiply the factorial variable by the current number
    fact *= num
    # decrement the current number by 1
    num -= 1

# print the final factorial value
print("Factorial =", fact)

In the above code, we first get the input number from the user using the input() function and convert it to an integer using the int() function.

We then initialize the factorial variable fact to 1 and use a while loop to calculate the factorial of the input number.

At each iteration of the loop, we multiply the current value of fact by the current value of num and decrement num by 1.

Finally, we exit the loop when num becomes 0 and prints the final value of a fact, which is the factorial of the input number.

Was this helpful?
YesNo

Related Articles:

Recent Articles:

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x