Write Python. Understand every error.

Open the editor

Python programs · Basics

Python program to check if a number is even or odd

A number is even when it divides by 2 with nothing left over. The remainder operator % tests exactly that.

Approach

  1. Read the number.
  2. Work out n % 2, the remainder after dividing by 2.
  3. If the remainder is 0 the number is even, otherwise it is odd.

The program

n = int(input())
if n % 2 == 0:
    print(n, "is even")
else:
    print(n, "is odd")

Sample run

Input
7
Output
7 is odd

Run this program in Py-CRAFT

How the code works

7 % 2 is 1, so 7 is odd, while 8 % 2 is 0, so 8 is even. The test also works for zero and for negative numbers, because Python's % gives a result from 0 upwards when the divisor is positive: -7 % 2 is 1.

Try changing it

Common mistakes

Learn the ideas

More programs

Share this page: