This Python program finds the factorial of a number using a loop.
Definition of the Factorial Function?
The factorial function is a mathematics formula represented by the exclamation mark "!". The formula finds the factorial of any number. It is defined as the product of a number containing all consecutive least value numbers up to that number. Thus it is the result of multiplying the descending series of numbers.
The factorial of zero is one, and the factorial is not defined for negative numbers.
Formula:
n! = n * (n-1) * (n-2) * … * 3 * 2 * 1
or
n! = 1 * 2 * 3 * ... * n
Examples of factorial formulas
Example:
0! = 1 1! = 1 2! = 1 * 2 = 2 3! = 1 * 2 * 3 = 6 4! = 4 * 3 * 2 * 1 = 24 5! = 5 * 4 * 3 * 2 * 1 = 5 * 24 = 120 7! = 7 * 6 * 5 * 4 * 3 * 2 * 1 = 5040
Python Program to Find Factorial
Program:
#Taking user input
n = int(input("Enter a number: "))
factorial = 1
if n < 0: #Check if the number is negative
print("Factors do not exist for negative numbers.")
elif n == 0: #Check if the number is zero
print("The factorial of 0 is 1.")
else:
for i in range(1,n + 1):
factorial = factorial*i
print("The factorial of",n,"is",factorial)
Program Output:
Enter a number: 5 The factorial of 5 is 120