Python Compute the Sum of All Numbers from 1 to n (Using Recursion)
We will use recursion to compute the sum of all integers from 1 to n. Recursion is a way of solving a problem by having a function call itself. In this example we define a function that keeps calling itself until it reaches the base case (that is, n equals 1), and then starts returning results.
Example
def
sum_recursive
(
n
)
:
if
n
==
1
:
return
1
else
:
return
n + sum_recursive
(
n -
1
)
Test the function
n
=
10
(
f
"The sum from 1 to {n} is: {sum_recursive(n)}"
)
Code analysis:
sum_recursive(n)is a recursive function used to compute the sum from 1 to n.- If both the
nequals 1, the function returns 1; this is the base case of the recursion. - Otherwise, the function returns
nplussum_recursive(n - 1), which is the recursive case. - In the test section we call
sum_recursive(10)to compute the sum from 1 to 10 and print the result.
Output result:
1 到 10 的总和是: 55
Python3 Examples