# How to Write Recursive Python Function to Find Factorial?

#### Cyber Security : Go from Zero to Hero

Most Popular

60 Lectures 5.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

#### C Programming from scratch- Master C Programming

Best Seller

60 Lectures 8 hours

Recursion is a powerful concept in computer science that allows a function to call itself in order to solve problems. One classic example of recursion is calculating factorials. In this article, we'll delve into the world of recursion in Python and learn how to write a recursive function to find factorials using python. We'll discuss the algorithm, provide programming examples with outputs, and include multiple test cases to ensure a thorough understanding.

Algorithm:

The factorial of a non-negative integer $$n$$, denoted as $$n!$$, is the product of all positive integers less than or equal to $$n$$.

Mathematically, it can be represented as:

$$n! = n * (n-1) * (n-2) * ... * 2 * 1$$

Here's how we can implement a recursive function to find the factorial of a given number n:

1. Base Case: If n is 0 or 1, return 1 (0! and 1! are both defined as 1).
2. Recursive Step: Otherwise, return n multiplied by the factorial of (n-1).

Now, let's translate this algorithm into Python code.

def factorial(n):
# Base Case
if n == 0 or n == 1:
return 1
# Recursive Step
else:
return n * factorial(n-1)

# Test cases
print("Factorial of 5:", factorial(5))
print("Factorial of 0:", factorial(0))
print("Factorial of 1:", factorial(1))


Outputs:

Factorial of 5: 120
Factorial of 0: 1
Factorial of 1: 1

Explanation:

1. In the first test case, we find the factorial of 5, which is $$5 * 4 * 3 * 2 * 1 = 120.$$
2. In the second and third test cases, we verify that the factorial function returns 1 for both 0! and 1!.

Multiple Test Cases:

Now, let's include additional test cases to further validate our recursive factorial function.

# Additional test cases
print("Factorial of 3:", factorial(3))
print("Factorial of 6:", factorial(6))
print("Factorial of 10:", factorial(10))


Factorial of 3: 6
Factorial of 6: 720
Factorial of 10: 3628800

### Conclusion:

In this article, we've explored the concept of recursion and applied it to calculate factorials in Python. By understanding the algorithm and implementing it in code, you now have the knowledge to write recursive functions for various mathematical calculations. Additionally, by including multiple test cases, you can ensure the correctness and efficiency of your recursive solutions. Keep practicing and experimenting with recursion to master this fundamental programming technique.