Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Compute the Sum of All Numbers from 1 to n (Using Recursion)

Python Compute the Sum of All Numbers from 1 to n (Using Recursion)

Document Object Reference Manual Python3 Examples

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

print

(

f

"The sum from 1 to {n} is: {sum_recursive(n)}"

)

Code analysis:

  1. sum_recursive(n) is a recursive function used to compute the sum from 1 to n.
  2. If both the n equals 1, the function returns 1; this is the base case of the recursion.
  3. Otherwise, the function returns n plus sum_recursive(n - 1) , which is the recursive case.
  4. 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

Document Object Reference Manual Python3 Examples