Here are ways to find the factorial of a number in Python:
- Using for loop
- Using Recursion
- Using math.factorial() method
- Using reduce() Function
One thing to remember is that the factorial of both 0! and 1! is 1. You can’t calculate the factorial of a negative number.
Method 1: Using for loop
Example
number = 6 # number = int(input("Enter a number: "))
factorial = 1
# Checking if the number is negative, zero, or positive
if number < 0:
print("Factorial cannot be calculated for negative numbers")
elif number == 0 or number == 1:
print(1)
else:
for i in range(1, number + 1):
factorial = factorial * i
print("Factorial of", number, "is:", factorial)
Output
Factorial of 6 is : 720
Method 2: Using Recursion
The recursive function calls itself with decreasing values of number until it reaches 1.
Example
def factorial_recursive(number):
if number < 0:
print("Factorial cannot be calculated for negative numbers")
elif number == 0 or number == 1:
return 1
else:
return number * factorial_recursive(number - 1)
# Call the factorial function and print the result
print("Factorial of 6 is : ", factorial_recursive(6))
Output
Factorial of 6 is: 720
Method 3: Using math.factorial() method
The factorial() method from the math module returns the factorial of a given non-negative integer.
Visual Representation
Example
import math
number = 6
if(number < 0):
print("Factorial cannot be calculated for negative numbers")
else:
print("Factorial of", number, "is:", math.factorial(number))
Output
Factorial of 6 is: 720
Method 4: Using reduce() Function
The reduce function applies the lambda function (which multiplies two numbers) cumulatively to the items, effectively calculating the product of all numbers from 1 to n.
Example
from functools import reduce
def factorial_reduce(number):
if number < 0:
return "Factorial cannot be calculated for negative numbers"
return reduce(lambda x, y: x*y, range(1, number+1)) if number > 0 else 1
print("Factorial of 6 is :", factorial_reduce(6))
Output
Factorial of 6 is: 720
That’s it.
Ankit Lathiya is a Master of Computer Application by education and Android and Laravel Developer by profession and one of the authors of this blog. He is also expert in JavaScript and Python development.