Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-mini-2024-07-18· OpenAIAi2 WildChat-4.8M (AI2)

Please, make a short example of recursion in python

  1. User

    Please, make a short example of recursion in python

  2. 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 factorial function calls itself with a decremented value of n until it reaches the base case where n is 0. The computed values are then multiplied together as the recursive calls return. The output for factorial(5) would be 120.