Program to find sum of even numbers in python

In this post, you will learn how to write a Python program to get the sum of even numbers. There are different ways to calculate the sum of even numbers. Here we have mentioned most of them-

Python program to calculate sum of even numbers using for loop

In the given program, we first take user input to enter the maximum limit value. Then, we have used the for loop to calculate the sum of even numbers from 1 to that user-entered value.

# Python Program to Calculate
# Sum of Even Numbers from 1 to N
 
max = int[input["Please enter the maximum value: "]]
total = 0

for num in range[1, max+1]:
    if[num % 2 == 0]:
        print["{0}".format[num]]
        total = total + num

print["The Sum of Even Numbers from 1 to {0} = {1}".format[num, total]]

Output of the above code:

Please enter the maximum value: 23
2
4
6
8
10
12
14
16
18
20
22
The Sum of Even Numbers from 1 to 23 = 132

Python program to calculate sum of even numbers using for loop without If Statement

In the given program, first we have taken user input to enter the maximum limit value. Then, we have used the for loop to calculate the sum of even numbers from 1 to that user-entered value without using if statement.

# Python program to calculate sum of even numbers 
# from 1 to N
 
max_num = int[input["Please enter the maximum value : "]]
total = 0

for num in range[2, max_num + 1, 2]:
    print["{0}".format[num]]
    total = total + num

print["The Sum of Even Numbers from 1 to {0} = {1}".format[num, total]]

Output of the above code

Please enter the maximum value : 20
2
4
6
8
10
12
14
16
18
20
The Sum of Even Numbers from 1 to 20 = 110

Python program to calculate sum of even numbers using while loop

In the given program, we have applied the same logic as above, just replaced the for loop with a while loop.

# Python program to calculate
# sum of even numbers from 1 to N
 
max = int[input["Please enter the maximum value:"]]
total = 0
num = 1
 
while num 

Chủ Đề