How can I calculate the factorial of a number using recursion in Python?

98 views

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
0

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: 120

Explanation:

  • The function factorial takes an integer n as input.
  • The base case is when n is 0 or 1, where the function returns 1.
  • For other values of n, the function calls itself recursively with n-1 and multiplies the result by n.
solveurit24@gmail.com Changed status to publish February 13, 2025
0
You are viewing 1 out of 1 answers, click here to view all answers.