Artificial Intelligence
Please fill the required field.

write a python function to calculate factorial using recursion. include the code in a properly formatted code block with syntax highlighting


Certainly! Here’s a Python function to calculate the factorial of a number using recursion: ```python def factorial(n): """Calculate the factorial of a number n using recursion.""" if n < 0: raise ValueError("Factorial is not defined for negative numbers") elif n == 0 or n == 1: return 1 else: return n * factorial(n - 1) # Example usage: # print(factorial(5)) # Output: 120 ``` In this function, we check if the input is a negative number, in which case we raise a `ValueError`. If the input is 0 or 1, we return 1, as the factorial of both these values is 1. For any other positive integer, we call the `factorial` function recursively. Update (2026-06-17): Here is a Python function that calculates the factorial of a number using recursion: ```python def factorial(n): if n < 0: raise ValueError("Factorial is not defined for negative numbers.") elif n == 0 or n == 1: return 1 else: return n * factorial(n - 1) # Example usage print(factorial(5)) # Output: 120 ``` This function checks if the input is negative and raises an exception if so. For the base cases of 0 and 1, it returns 1. Otherwise, it computes the factorial recursively.