English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Python Functions

Python Data Types

Python file operations

Python objects and classes

Python date and time

Advanced knowledge of Python

Python reference manual

Python program to calculate the sum of natural numbers

Python example大全

In this program, you will learn to use the recursive function to calculate the sum of natural numbers.

To understand this example, you should understand the followingPython programmingTopic:

In the following program, we use the recursive function recur_sum() to calculate the total sum of the given numbers.

Source code

# Python program to calculate the sum of natural numbers
def recur_sum(n):
   if n <= 1:
       return n
   else:
       return n + recur_sum(n-1)
# Change this value to get different results
num = 16
if num < 0:
   print("Enter a positive number")
else:
   print("The sum is", recur_sum(num))

Output result

The sum is 136

Note:To test another number in the program, please change the value of num.

Python example大全