Python Calculate the sum of all numbers from 1 to n (using recursion)

Document 对象参考手册Python3 Examples

We will use recursion to calculate the sum of all integers from 1 to n. Recursion is a method of solving problems by having a function call itself. In this example, we will define a function that keeps calling itself until it reaches the base case (i.e., n equals 1), then starts returning results.

Example

def sum_recursive(n):
    if n == 1:
        return 1
    else:
        return n + sum_recursive(n - 1)

# Test function
n = 10
print(f"The sum from 1 to {n} is: {sum_recursive(n)}")

Code analysis:

  1. sum_recursive(n)is a recursive function used to calculate the sum from 1 to n.
  2. Ifnequals 1, the function returns 1, which is the base case of recursion.
  3. Otherwise, the function returnsnplussum_recursive(n - 1)the result of ..., which is the recursive case.
  4. In the test section, we callsum_recursive(10)to calculate the sum from 1 to 10, and print the result.

Output result:

1 到 10 的总和是: 55

Document 对象参考手册Python3 Examples

Other extensions