Sum of n numbers in Python using for loop
In this post, you will learn a Python program to find the sum of n numbers using a for loop.
In the given Python program, we have used the for loop to calculate the sum of n numbers. First, we have taken an int data type number input from the user and stored it in a variable num. Initially, the sum is initialised to 0. Then, we used the for loop for iteration in the range from 1 to num + 1 to increase the number up to the given input. In each iteration, we have added the value to the sum and, at last, printed the sum variable.
Algorithm
- Read the input (num) from the user.
- Initialize a variable sum with zero.
- Use a for loop to iterate from 1 to num.
- Inside the loop, add the num to the sum.
- At the end, print the value of the sum.
Python Program to find sum of n numbers using for loop
# Sum of natural numbers up to num
num = int(input("Please enter the number: "))
sum = 0
for value in range(1, num + 1):
sum = sum + value
print(sum)
Output1:
Please enter the number: 20
210
We can see the sum of the number till 20 is 210 as the output.
Output2:
Please enter the number: 12
78
Output3:
Please enter the number: 23
276
Related Articles
Sum of even numbers in PythonSwapping of two numbers in Python
Find average of n numbers in Python
Python program to print all even numbers between 1 to 100
Sum of n numbers in Python using while loop
Python program to list even and odd numbers of a list
Python program to print odd numbers within a given range
Python program to multiply two numbers
Program to find area of triangle in Python
Find area of rectangle in Python
Swapping of two numbers in Python
Find average of n numbers in Python
Print multiplication table in Python
Python program to multiply two matrices
Python program to find area of circle
Python iterate list with index
Python add list to list
Python random choice
Python dict inside list
Count consonants in a string Python
Convert array to list Python