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

Python basic tutorial

Python flow control

Python Functions

Python Data Types

Python file operation

Python object and class

Python date and time

Python advanced knowledge

Python reference manual

Python program to calculate the sum of natural numbers

Python example大全

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

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 a 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 a 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 formula above to find the sum of natural numbers.

Python example大全