A non-negative integer’s factorial is the multiplication of all integers less than or equal to n.
n = int(input("Enter a number: "))
fact = 1
if n < 0:
print(" Factorial does not exist for negative numbers")
elif n == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,n + 1):
fact = fact*i
print("The factorial of",n ,"is",fact)
Output:
Enter a number: 9
The factorial of 9 is 362880
Contents
Using Recursion
def factorial(num):
return 1 if (num==1 or num==0) else num * factorial(num - 1);
n = int(input("Enter a number: "))
print("Factorial of",n,"is", factorial(n))
Output:
Enter a number: 7
Factorial of 7 is 5040
Using built-in function
Math module includes the build-in factorial() method.
import math
def factorial(num):
return(math.factorial(num))
n = int(input("Enter the number:"))
fact = factorial(n)
print("Factorial of", n, "is", fact)
Output:
Enter the number: 6
Factorial of 6 is 720