Write a Python Program to Calculate the Sum of Even Numbers from 1 to N using the While Loop and For Loop with an example.
Python Program to Calculate Sum of Even Numbers from 1 to N using For Loop
This Python program allows the user to enter the maximum limit value. Next, it is going to calculate the sum of even numbers from 1 to that user-entered value.
In this example, we are using Python For Loop to keep the number between 1 and the maximum value.
TIP: I suggest you refer to the Python Even Numbers from 1 to N article to understand the logic behind printing Even numbers in Python.
# Calculate Sum of Even Numbers from 1 to N
maximum = int(input(" Please Enter the Maximum Value : "))
total = 0
for number in range(1, maximum+1):
if(number % 2 == 0):
print("{0}".format(number))
total = total + number
print("The Sum of Even Numbers from 1 to {0} = {1}".format(number, total))
The sum of even numbers output
Please Enter the Maximum Value : 15
2
4
6
8
10
12
14
The Sum of Even Numbers from 1 to 15 = 56
Python Program to Calculate Sum of Even Numbers from 1 to N without If Statement
This sum of even numbers example program is the same as above. But we altered the Python For Loop to remove If block.
# Calculate Sum of Even Numbers from 1 to N
maximum = int(input(" Please Enter the Maximum Value : "))
total = 0
for number in range(2, maximum + 1, 2):
print("{0}".format(number))
total = total + number
print("The Sum of Even Numbers from 1 to {0} = {1}".format(number, total))
The sum of even numbers using a for loop output
Please Enter the Maximum Value : 12
2
4
6
8
10
12
The Sum of Even Numbers from 1 to 12 = 42
Program to find the Sum of Even Numbers using While Loop
In this sum of even numbers example, we replaced the For Loop with While Loop.
# Calculate Sum of Even Numbers from 1 to N
maximum = int(input(" Please Enter the Maximum Value : "))
total = 0
number = 1
while number <= maximum:
if(number % 2 == 0):
print("{0}".format(number))
total = total + number
number = number + 1
print("The Sum of Even Numbers from 1 to N = {0}".format(total))
Python sum of even numbers using a while loop output
Please Enter the Maximum Value : 20
2
4
6
8
10
12
14
16
18
20
The Sum of Even Numbers from 1 to N = 110
Program to find the Sum of Even Numbers from 1 to 100
This Python program allows users to enter Minimum and maximum values. Next, it calculates the sum of even numbers from the Minimum to the maximum value.
# Calculate Sum of Even Numbers from 1 to 100
minimum = int(input(" Please Enter the Minimum Value : "))
maximum = int(input(" Please Enter the Maximum Value : "))
total = 0
for number in range(minimum, maximum+1):
if(number % 2 == 0):
print("{0}".format(number))
total = total + number
print("The Sum of Even Numbers from {0} to {1} = {2}".format(minimum, number, total))