Factorial in python is denoted by (!). It is the process of multiplying all the whole numbers from the chosen number till 1 and returning the output. For example the factorial of 4 is:
4! = 4x3x2x1
This is equal to 24. Hence the factorial of 4! is 24. In some mathematical terms, 4 factorial is also termed as 4 bang.
The rule of calculating factorial in python is:
n!= n x (n-1)!
This statement means the factorial of a number is the number itself times the number of that factorial minus one. There is a very interesting fact behind factorial of a number is that factorial of 0! is always 1. Factorial of 1 is also 1 always. The use of factorial value is done the places where one wants to use permutations and combinations.
Another interesting fact about factorial is that negative number in mathematics does not have factorial values. For example, there is no factorial value for -1. However, decimal values can have factorial values. For that process, the user needs to have knowledge about gamma function in Mathematics. The code tends to give ValueError exception if the integer is negative or non integer value.
Python program to find factorial using for loop
x = 6 #Give number to find factorial factorial = 1 if x < 0: print("Sorry, factorial does not exist for negative numbers") elif x == 0: print("The factorial of 0 is 1") else: for i in range(1,x + 1): factorial = factorial * i print("The factorial of",x,"would be",factorial)
The output of this python program will be:
The factorial of 6 would be 720
In python, the user doesn’t always need to write the whole python code. There is another way for computing the factorial of a program. There is a simpler way which is by using factorial() function in python. This function is found under math section in python. Implementation of a program using math.factorial is always fast as it has C type implementation.
Python program to find the factorial of a number provided by the user
num = int(input("Enter the number: ")) fact = 1 #To check if the number is negative, positive or zero if num < 0: print("The output is not valid") elif num == 0: print ("The factorial of 0 is 1") else: for i in range(1,num + 1): fact = fact*i print ("Factorial of %d is %d" %(num, fact))
The output of this python program using factorial() will be:
Enter the number: 6 Factorial of 6 is 720
- Factorial of 1 is always 1.
- The factorial of 0 is always 1.
- The formula for calculating factorial of an integer is:
n!= n x (n-1)!