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
PHP Star Triangle pattern program In this tutorial, we will discuss about PHP Star Triangle…
PHP Full Pyramid pattern program In this tutorial, we will discuss about PHP Full Pyramid…
5 methods to add two numbers in Java In this tutorial, we will discuss the…
Python full Pyramid star pattern program In this tutorial, we will discuss the concept of…
Write a function or method to convert C into F -Entered by the user In…
How to write a function or method to convert Celsius into Fahrenheit In this tutorial,…