gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
Please, make a short example of recursion in python
- User
Please, make a short example of recursion in python
- Assistant
Certainly! Here's a simple example of recursion in Python that calculates the factorial of a number:
def factorial(n): # Base case: if n is 0, the factorial is 1. if n == 0: return 1 else: # Recursive case: n! = n * (n - 1)! return n * factorial(n - 1) # Example usage number = 5 result = factorial(number) print(f"The factorial of {number} is {result}.")In this example, the
factorialfunction calls itself with a decremented value ofnuntil it reaches the base case wherenis 0. The computed values are then multiplied together as the recursive calls return. The output forfactorial(5)would be120.