Write a Python Program to Calculate Sum of Even Numbers from 1 to N using 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, Python 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 maximum value.
TIP: I suggest you refer to Python Even Numbers from 1 to N article to understand the logic behind printing Even numbers in Python.
# Python Program to 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))
Python 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 Python sum of even numbers program is the same as above. But we altered the Python For Loop to remove If block.
# Python Program to 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))
Python 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
Python Program to find Sum of Even Numbers using While Loop
In this Python sum of even numbers example, we replaced the For Loop with While Loop.
# Python Program to 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
Python Program to find Sum of Even Numbers from 1 to 100
This Python program allows users to enter Minimum and maximum value. Next, Python calculates the sum of even numbers from Minimum to the maximum value.
# Python Program to 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))
