In this post, we will learn how to do the sum of even numbers in python using while-loop, for-loop, and function with detailed explanations and algorithms.

But before jumping into the algorithm or coding part let’s first understand what is even number.

What is an Even number?

An Even number is a number that is only divisible by 2.

For Example 0,2, 4, 6, 8, 10, 12, 14, 16,…

Algorithm

  1. Take input from the User (num).
  2. Take one variable sum and initially, it is zero.
  3. i = 0
  4. while i <= num check
    if i % 2 == 0 then do
    sum +=i and exit from if-block
    i+=1
  5. At last print(sum)

From the above algorithm, we know how to do the sum of even numbers in python. So now let’s start writing a program.

Sum of even numbers in python Using while loop

Before writing this program few programming concepts you have to know:

  1. How to take input from the user
  2. if-else
  3. while- loop

Source Code

num = int(input('Enter a number: '))
sum = 0
i = 0
while i <= num:
    if i % 2 == 0:
        print(i)
        sum+=i
    i+=1
print(f"Sum of all the even numbers is {sum}")

Output

Enter a number: 10
0
2
4
6
8
10
Sum of all the even numbers is 30

Sum of even numbers in python Using for loop

Few programming concepts you have to know before writing this program:

  1. How to take input from the user
  2. if-else
  3. for- loop

NOTE: For this program, the above algorithm is being used, only the syntax has been changed.

Source Code

num = int(input('Enter a number: '))
sum = 0
for i in range(0, num+1):
    if i % 2 == 0:
        print(i)
        sum+=i

print(f"Sum of all the even numbers is {sum}")

Output

Enter a number: 20
0
2
4
6
8
10
12
14
16
18
20
Sum of all the even numbers is 110

Sum of even numbers in python Using function

Before writing this program few programming concepts you have to know:

  1. How to take input from the user
  2. if-else
  3. for- loop
  4. Python Functions

Source Code

def Sum_of_Even(n):
    sum = 0
    for i in range(0, n+1):
        if i % 2 == 0:
            print(i)
            sum+=i
    return sum
   
num = int(input('Enter a number: '))
print(f"Sum of all the even numbers is {Sum_of_Even(num)}")

Output

Enter a number: 30
0
2
4
6
8
10
12
14
16
18
20
22
24
26
28
30
Sum of all the even numbers is 240
Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Write A Comment