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
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
C# inverted full pyramid star pattern In this article, we will discuss the concept of…
C# Full Pyramid star pattern program In this article, we will discuss the concept of…
Program to count vowels, consonants, words, characters and space in Java In this article, we…
How to print multiplication table using Array in C++ language In this post, we will…
C Program to multiplication table using Array In this tutorial , we will discuss about…
Java program to check odd or even using recursion In this tutorial, we discuss a…