π Day 93/150 – Recursive Factorial in Python
Recursion is a programming technique where a function calls itself to solve a smaller version of the same problem. One of the most common examples of recursion is calculating the factorial of a number.
The factorial of a positive integer n is the product of all positive integers from 1 to n.Formula:
5! = 5 × 4 × 3 × 2 × 1 = 120In this post, we'll explore four different ways to calculate the factorial of a number using recursion and related approaches.
Method 1 – Basic Recursive Function
A recursive function calls itself until it reaches the base case.
def factorial(n): if n == 0 or n == 1: return 1 return n * factorial(n - 1) print(factorial(5))
Output
120
Explanation
-
If n is 0 or 1, the function returns 1.
- Otherwise, it returns n × factorial(n - 1).
The function keeps calling itself until the base case is reached.
Method 2 – Taking User Input
Calculate the factorial recursively using user input.
6def factorial(n): if n == 0 or n == 1: return 1 return n * factorial(n - 1) num = int(input("Enter a number: ")) print("Factorial:", factorial(num))
Sample Input
Output
Factorial: 720
Explanation
- The user enters a number.
- The recursive function calculates its factorial.
- The result is displayed.
Method 3 – Recursive Function with Error Handling
Prevent negative numbers from being processed.
Factorial is not defined for negative numbers.def factorial(n): if n < 0: return "Factorial is not defined for negative numbers." if n == 0 or n == 1: return 1 return n * factorial(n - 1) print(factorial(-3))
Output
Explanation
- The function first checks for negative numbers.
- If the input is negative, it returns an error message.
- Otherwise, recursion continues normally.
Method 4 – Recursive Function with Default Argument
Use a default argument to calculate the factorial of 5 if no value is provided.def factorial(n=5): if n == 0 or n == 1: return 1 return n * factorial(n - 1) print(factorial()) print(factorial(4))
Explanation
- The function first checks whether the position is negative.
- If it is, an error message is returned.
- Otherwise, recursion proceeds normally.
Output
120 24
Explanation
Comparison of Methods
| Method | Best For |
|---|---|
| Basic Recursion | Learning recursion |
| User Input | Interactive programs |
| Error Handling | Validating input |
| Default Argument | Optional function parameters |
π₯ Key Takeaways
- Recursion is a technique where a function calls itself.
- Every recursive function must have a base case to stop the recursion.
- Factorial is one of the best examples for understanding recursion.
- Always validate input before performing recursive calculations.
- While recursion is elegant, iterative solutions are often more memory-efficient for very large inputs.
.png)

0 Comments:
Post a Comment