The best way to calculate Factorial in Python is using recursion function.
def factorial(number):
# Check that the input is an integer before doing factorial math
if not isinstance(number, int):
raise TypeError("Sorry! Number must be an integer.")
# Check if the input is a zero or a positive number
if number < 0:
raise ValueError("Sorry! Number must be zero or positive number.")
def inner_factorial(number):
# Base case: 0! and 1! are both 1
if number <= 1:
return 1
# Recursive case: n! = n * (n - 1)!
return number * inner_factorial(number - 1)
# Start the recursive factorial calculation
return inner_factorial(number)
# Print the factorial of 4.
print(factorial(4))
Output:
24