Using Python, we can calculate factorials using recursion. Defining a recursive function to find the factorial of a nonnegative integer in Python can be done in the following code.
def factorial_with_recursion(n):
if isinstance(n,int) and n >= 0:
if n == 0 or n == 1:
return 1
else:
return n * factorial_with_recursion(n-1)
else:
return "Not valid input"
When working with numbers, one common calculation which is easy to perform in Python is finding the factorial of a number.
We can find the factorial of a number in Python in a number of ways.
One such way is to use recursion to calculate the factorial of a number.
To use recursion, we need to define a base case for our recursive function, and define the recursive step where we will call the recursive function again.
Using Recursion to Calculate Factorial of Number in Python
Finding the factorial of a number using recursion is easy. To calculate the factorial of a number in Python using recursion, we need to define the base case, and then define the recursive step.
The base case for the factorial function is when n is 0 or 1. In that case, we want to return 1. If n is greater than 1, then we will call the function again with n – 1 as the input.
Below is a recursive function for calculating the factorial of a number. I’ve also included some input validation to make sure that the input is a nonnegative integer.
def factorial_with_recursion(n):
if isinstance(n,int) and n >= 0:
if n == 0 or n == 1:
return 1
else:
return n * factorial_with_recursion(n-1)
else:
return "Not valid input"
print(factorial_with_recursion(3))
print(factorial_with_recursion(5))
print(factorial_with_recursion(8))
print(factorial_with_recursion(12))
#Output:
6
120
40320
479001600
As you can see above, calculating the factorial of a number in Python using a recursive function is pretty straightforward.
Hopefully this article has been useful for you to learn how to use Python to calculate the factorial of a number using recursion.