Python Calculate the sum of all numbers from 1 to n (using recursion)
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)}")
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:
sum_recursive(n)is a recursive function used to calculate the sum from 1 to n.- If
nequals 1, the function returns 1, which is the base case of recursion. - Otherwise, the function returns
nplussum_recursive(n - 1)the result of ..., which is the recursive case. - In the test section, we call
sum_recursive(10)to calculate the sum from 1 to 10, and print the result.
Output result:
1 到 10 的总和是: 55Other extensions
Python3 Examples