The factorial(!) of a number n is the product of all positive numbers less than or equal to n.
The factorial of a number is defined as:
Note: The factorial of 0 is 1.
To calculate the factorial of 4, have a look at the following illustration:
In Python, there are two approaches to computing the factorial of a number:
The following code explains how to compute the factorial of a number using the iterative approach:
def factorial(n):fact = 1for num in range(2, n + 1):fact *= numreturn fact
The iterative approach works by setting a base value to . For each loop, the method multiplies to the base value until the for
loop finishes and you get the final factorial value.
The recursive approach is when the function calls itself again and again until some stopping condition. It has two parts:
This is where the recursion stops
This is the case where the function calls itself again and again until the base condition is reached.
The following illustration explains how to compute the factorial of a number using recursion in Python:
def factorial(n):if n == 1: #base casereturn nelse:return n*factorial(n-1) # recursive casenumber = 4if number < 0:print("Factorial exists for positive numbers only")elif number == 0:print("Factorial of 0 : 1")else:print("Factorial of",number,":",factorial(number))
Free Resources