Python Program to Check Whether a Number Is Even or Odd
Beginner · Basics
An even number divides exactly by 2, like 4, 10 and 0, while an odd number leaves a remainder of 1, like 7 and 15. This program uses the remainder operator % to find out which kind a number is.
Program
17 is an odd number
How it works
- The
%operator gives the remainder after division, sonum % 2is 0 for even numbers and 1 for odd numbers. - If the remainder is 0, the
ifbranch prints that the number is even. - Otherwise the
elsebranch prints that it is odd. - This also works for negative numbers, because in Python
-7 % 2is 1.
Other ways to write it
Checking a list of numbers
4 is even 7 is odd 10 is even -3 is odd 0 is even
A conditional expression picks the word "even" or "odd" in one line, inside a loop over several numbers.
Using the bitwise AND operator
42 is even
num & 1 keeps only the last binary digit, which is 1 for odd numbers and 0 for even ones.
Try it yourself
Change the program to print every even number from 1 to 20.
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.
For a practical file: draw its flowchart or write its algorithm in steps.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises