Skip to content
Devtoolry

Basics · beginner

Python Program to Check if a Number is Even or Odd

Check whether a number is even or odd in Python with the modulo operator (%), including negative numbers, plus a short version with a conditional expression.

A number is even when it divides by 2 with nothing left over. The modulo operator % gives exactly that leftover, so n % 2 is 0 for even numbers and 1 for odd ones.

The program checks several numbers in a loop, including zero and a negative number, so you can see that the rule holds for all of them.

The program

Python
for n in [7, 12, 0, -3]:
    if n % 2 == 0:
        print(n, "is even")
    else:
        print(n, "is odd")
Output
7 is odd
12 is even
0 is even
-3 is odd

How it works

  1. The for loop gives n each value of the list in turn.
  2. n % 2 is the remainder after dividing by 2: 7 % 2 is 1, 12 % 2 is 0.
  3. If the remainder is 0 the number is even, otherwise it is odd.
  4. Zero is even (0 % 2 is 0). In Python, -3 % 2 is 1, because the result of % takes the sign of the divisor, so negative numbers work too.

Watch it run line by line

Step through the loop and watch n change in the global frame. The highlighted line jumps to either the even or the odd print, never both.

“Visualize step by step” opens the program in the Python Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.

Another way: One line with a conditional expression

A conditional expression picks one of two values. It is handy inside an f-string or when you need the word as a value.

Python
n = 15
print(f"{n} is {'even' if n % 2 == 0 else 'odd'}")
Output
15 is odd

Common mistakes

  • Writing n % 2 == 1 for odd numbers works in Python, but it breaks in languages where -3 % 2 is -1. Testing == 0 for even is safe everywhere.
  • Using a single = in the condition (if n % 2 = 0) is a SyntaxError: = assigns, == compares.
  • Reading the number with input() and forgetting int(): "7" % 2 raises TypeError.

Try it yourself

  • Count how many even and how many odd numbers are in a list.
  • Print every even number from 1 to 20 using range(2, 21, 2).

Open the program in the Python Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 Python examples, or write your own program in the online Python Compiler.