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
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
range(start, end + 1)goes through every whole number fromstarttoend; the+ 1is needed becauserange()stops just before its second value.num % 2 == 0is true when dividing by 2 leaves no remainder, which is what makes a number even.end=" "prints the numbers on one line, and the emptyprint()ends that line afterwards.countandtotalchange only for even numbers, giving 10 numbers with a sum of 110.
Other ways to write it
Using range() with a step of 2
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: [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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises