Editor

Python Program to Print Even Numbers in a Range

Beginner · Basics

An even number is a whole number that divides by 2 with nothing left over, such as 2, 10 and 36. This program prints all the even numbers in a range, then counts them and adds them up.

Program

print_even_numbers.py
start = 1 # or: start = int(input("Enter the start of the range: "))
end = 20 # or: end = int(input("Enter the end of the range: "))
count = 0
total = 0
print(f"Even numbers from {start} to {end}:")
for num in range(start, end + 1):
if num % 2 == 0: # no remainder when divided by 2
print(num, end=" ")
count += 1
total += num
print()
print("How many:", count)
print("Their sum:", total)
Output
Even numbers from 1 to 20:
2 4 6 8 10 12 14 16 18 20 
How many: 10
Their sum: 110

How it works

  1. range(start, end + 1) goes through every whole number from start to end; the + 1 is needed because range() stops just before its second value.
  2. num % 2 == 0 is true when dividing by 2 leaves no remainder, which is what makes a number even.
  3. end=" " prints the numbers on one line, and the empty print() ends that line afterwards.
  4. count and total change only for even numbers, giving 10 numbers with a sum of 110.

Other ways to write it

Using range() with a step of 2

Using range() with a step of 2
start, end = 1, 20
first = start if start % 2 == 0 else start + 1 # the first even number
evens = list(range(first, end + 1, 2))
print("Even numbers:", evens)
print("Sum:", sum(evens))
Output
Even numbers: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Sum: 110

Starting at the first even number and stepping by 2 skips the odd numbers completely, so no if is needed and the loop does half the work.

Even and odd numbers with list comprehensions

Even and odd numbers with list comprehensions
numbers = range(1, 21)
evens = [n for n in numbers if n % 2 == 0]
odds = [n for n in numbers if n % 2 != 0]
print("Even:", evens)
print("Odd: ", odds)
Output
Even: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Odd:  [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

A list comprehension builds a list from a loop and a condition in one line, so the even and the odd numbers each take a single line.

Try it yourself

Change the program to print the odd numbers in the range instead, and check that their sum is 100.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises