Skip to content

Sum of n even numbers in Python using while loop

  • by

In general, even numbers are those numbers that are divisible by 2. So you have to implement this logic inside the iteration to check whether the number is even or not then add it to get the Sum of n even numbers in Python using a while loop.

Sum of n even numbers in Python using while loop

Simple example code.

my_list = [2, 4, 6, 8]
count = len(my_list) - 1
sum = 0

while count >= 0:
    if my_list[count] % 2 == 0:
        sum = sum + my_list[count]
    count = count - 1

print("While loop Sum", sum)

Output:

Sum of n even numbers in Python using while loop

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.

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))

Output:

 Please Enter the Maximum Value : 10
2
4
6
8
10
The Sum of Even Numbers from 1 to N = 30

Comment if you have any doubts or suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *