Statement
Solution
Python Exercise 6.3: Recursive Factorial
Calculate factorial using recursion (function calling itself).
Your program should:
- Define a recursive function
factorial(n). - Base case: if n == 0 or n == 1, return 1.
- Recursive case: return n * factorial(n-1).
- Test with user input.
Sample Interaction:
Input
Output
5
120
Solution
Here is the recursive factorial function.
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Test the function
n = int(input("Enter n: "))
print(factorial(n))
Key Concepts:
- Recursion calls the function itself.
- Base case prevents infinite recursion.
- Recursive case breaks down the problem.
Test Console
Run code to see output...