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

Python basic tutorial

Python flow control

Fonction en Python

Types de données en Python

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 examples in full

In this program, you will learn to use the while loop to calculate the sum of n natural numbers and display them.

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

In the following program, we use an if...else statement combined with a while loop to calculate the sum of natural numbers up to num.

Source code

# Sum of natural numbers not exceeding num
num = 16
if num < 0:
   print("Enter a positive number")
else:
   sum = 0
   # Use the while loop to iterate until zero
   while(num > 0):
       sum += num
       num -= 1
   print("Sum", sum)

Output result

Sum 136

Note:To test the program with other numbers, please change the value of num.

Initially, initialize sum to 0. Then, store the number in the variable num.

Then, we use the while loop for iteration until num becomes zero. In each iteration of the loop, we add num to sum, and the value of num is reduced by1.

By using the following formula, we can solve the above problem without using a loop.

n*(n+1)/2

For example, ifn = 16Then the sum is(16 * 17)/ 2 = 136.

It's your turn:Modify the above program using the above formula to find the sum of natural numbers.

Python examples in full