Sum-of-Natural-Numbers in Python

Sum of Natural Numbers in Python

Write a program which finds sum of natural numbers in Python.

To understand sum of natural numbers in Python, first understand natural numbers.

Set of natural numbers are denoted by N and it is positive whole numbers without having element  zero i.e N={1, 2, 3, 4, 5, 6,………..}.

In this program I will add first four elements of natural numbers i.e sum=1+2+3+4 that would be equal to 10.


sum=0
i=1
while i <=4:
     sum=sum+i
     i=i+1               
print(sum)

If you see the code first line is sum=0, it means sum refers value 0.

Second line is i=1 it means i refers value 1.

Third line is while loop which is a compound statement which  checks whether i less than 4. If i is less than 4  control will enter inside while loop and executes two statements.

sum=sum+i
i=i+1

Further, to make  you understand while  loop very well, I have made a table in which columns are  variables and expression and rows are updated values of variables.

To understand very clearly see the video below.

 

 

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

©Postnetwork-All rights reserved.