Skip to content
The Chat Archive
deepseek-v3-0324· DeepSeek LMArena Human Preference 140K

create a simple python program that contains recursion

  1. User

    create a simple python program that contains recursion

  2. Assistant

    Here’s a simple Python program that demonstrates recursion by calculating the factorial of a number (n!).

    Factorial Using Recursion

    The factorial of a number n (denoted as n!) is the product of all positive integers from 1 to n.
    For example:

    • 5! = 5 × 4 × 3 × 2 × 1 = 120
    • 0! = 1 (by definition)

    Python Code

    def factorial(n):
        # Base case: 0! = 1
        if n == 0:
            return 1
        # Recursive case: n! = n × (n-1)!
        else:
            return n * factorial(n - 1)
    
    # Test the function
    number = 5
    print(f"The factorial of {number} is {factorial(number)}")
    

    Output

    The factorial of 5 is 120
    

    How It Works

    1. Base Case (n == 0) → Stops recursion and returns 1.
    2. Recursive Case (n > 0) → Calls factorial(n - 1) and multiplies it by n.

    Recursion Breakdown for factorial(5)

    factorial(5)  
    = 5 × factorial(4)  
    = 5 × 4 × factorial(3)  
    = 5 × 4 × 3 × factorial(2)  
    = 5 × 4 × 3 × 2 × factorial(1)  
    = 5 × 4 × 3 × 2 × 1 × factorial(0)  
    = 5 × 4 × 3 × 2 × 1 × 1  
    = 120  
    

    Alternative: Fibonacci Sequence (Another Recursion Example)

    def fibonacci(n):
        if n <= 1:
            return n
        else:
            return fibonacci(n - 1) + fibonacci(n - 2)
    
    print(fibonacci(7))  # Output: 13 (0, 1, 1, 2, 3, 5, 8, 13)
    

    Would you like another recursion example (e.g., binary search, tree traversal)? 😊

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.