How can I calculate the factorial of a number using recursion in Python?
How can I calculate the factorial of a number using recursion in Python?
How can I calculate the factorial of a number using recursion in Python?
solveurit24@gmail.com Changed status to publish February 13, 2025
The factorial of a number n (denoted as n!) is the product of all positive integers from 1 to n. We can calculate it using recursion in Python. Here’s an example:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Example usage:
print(factorial(5)) # Output: 120Explanation:
- The function
factorialtakes an integernas input. - The base case is when
nis 0 or 1, where the function returns 1. - For other values of
n, the function calls itself recursively withn-1and multiplies the result byn.
solveurit24@gmail.com Changed status to publish February 13, 2025