Editor

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

even_or_odd.py
num = 17 # or: num = int(input("Enter a number: "))
# The remainder after dividing by 2 is 0 for even numbers, 1 for odd ones
if num % 2 == 0:
print(num, "is an even number")
else:
print(num, "is an odd number")
Output
17 is an odd number

How it works

  1. The % operator gives the remainder after division, so num % 2 is 0 for even numbers and 1 for odd numbers.
  2. If the remainder is 0, the if branch prints that the number is even.
  3. Otherwise the else branch prints that it is odd.
  4. This also works for negative numbers, because in Python -7 % 2 is 1.

Other ways to write it

Checking a list of numbers

Checking a list of numbers
numbers = [4, 7, 10, -3, 0]
for num in numbers:
kind = "even" if num % 2 == 0 else "odd"
print(num, "is", kind)
Output
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

Using the bitwise AND operator
num = 42
# The last binary digit of an odd number is 1
if num & 1:
print(num, "is odd")
else:
print(num, "is even")
Output
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.

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