Calculate the sum of natural numbers in Python
Calculate the sum of natural numbers in Python
In this tutorial, we will discuss a concept of Python program to calculate the sum of natural numbers using loops
In this article, we are going to learn how to find the sum of natural numbers using loops in the Python programming language
Python program to find the sum of natural numbers using loop
Python code to find the sum of numbers using for loop
Program 1
This program takes input from the user and stores in variable num. Then, the for loop is used to calculate the sum of natural numbers up to the given number.
#Python program to calculate sum of natural numbers num=input("Enter numbet to calculate sum: ") #received input from the user num=int(num) sum=0; for number in range(0,num+1,1): sum=sum+number print("Sum of first ",num,"natural numbers is:",sum )
When the above code is executed, it produces the following results
Enter numbet to calculate sum: 20 Sum of first 20 natural numbers is: 210
Program 2
This program takes input from the user and stores in variable num. Then, the while loop is used to calculate the sum of natural numbers up to the given number
#Python program to calculate sum of natural numbers num=input("Enter numbet to calculate sum: ") num=int(num) sum=0; if num<0: print("Enter a positive number") else: while(num>0): sum=sum+num num-=1; print("Sum is:",sum )
When the above code is executed, it produces the following results
Enter numbet to calculate sum: 10 Sum is: 55
Similar post
C++ program to find the sum of natural numbers using loops
Java program to find the sum of natural numbers using loops
C program to find the sum of natural numbers using loops
Suggested for you