Before going to the program first let us understand what is a Factorial of a Number?
Factorial of a Number:
The factorial of a Number n, denoted by n! is the product of all positive integers less than or equal to n.
The value of 0! is 1 according to the convention for an empty product.
For example,
5! = 5 * 4 * 3 * 2 * 1 = 120
Program code for Factorial of a Number in Python:
# Python program to find the factorial of a number #Define a factorial and loop variable fact = 1 i = 1 # To take input from the user num = int(input("Enter a number: ")) # check if the number is negative or positive if num < 0: print("Sorry, factorial does not exist for negative numbers") else: while i <= num: fact = fact*i i = i + 1 print("The factorial of", num, "is", fact)
Related: Python Program to Find Factorial of a Number Using For Loop
Working:
- First, the computer reads the number to find the factorial of the number from the user.
- Then using a while loop the value of ‘i’ is multiplied by the value of ‘fact’.
- The loop continues till the value of ‘num’. Finally, the factorial value of the given number is printed.