In this article, we would discuss how to find factorial of a number through Python program. First, we would illustrate it using for loop and if-else statement. Subsequently, to get the desired outcome we will use factorial function defined in math module.
We can calculate factorial value of only positive integers. Therefore, we would write appropriate code while using for loop and if-else statement. On the other hand, factorial function itself takes care of such anomalies (i.e. negative values).
Factorial of a number (n) is the product of all numbers from 1 to n.
For instance, factorial of 7 is –
In addition to, factorial of 0 is 1.
Find factorial using for loop and if-else statement
#Ask the user to input a number x=int(input("Enter a number: ")) fact=1 if x==0: print("The factorial of 0 is 1") elif x<0: print("The factorial exists only for positive integers") else: for i in range(1,x+1): fact=fact*i print("The factorial of ",x," is", fact)
Herein, variable x stores the value entered by user. Thereafter, it is checked for three conditions. First two conditions are self-explanatory. But, if the value entered by user is greater than 0 then it invokes for loop. The range of for loop here is 1 to x. And, the fact variable stores the resultant value. Initial value of fact variable is 1.
So, if the user enters x as 7. Then, for loop runs for i = 1 to 7 and fact variable value gets updated every time. When the for loop has run its course, we get the result 5040.
Find factorial using factorial() function
Alternately, we can use factorial() function to get the desired outcome. For that, we need to first import math module.
#Ask the user to input a number x=int(input("Enter a number: ")) import math fact=math.factorial(x) print("The factorial of ",x," is", fact)
We cannot use functions provided through math module with complex numbers. To use factorial function, we have used math.factorial() and stored the resultant value in variable fact. The program would work for all positive integer values. It will return output as 1 for 0!. But, for negative values, it will throw a ValueError exception –
ValueError: factorial() not defined for negative values
In conclusion, we have discussed how to find factorial of a number through Python program.
Additional Info:
It is necessary to properly use indentation in Python. Otherwise, it may throw IndentationError exception.