Even or Odd Program in Python
Problem statement
Read a number and print whether it is even or odd. Zero counts as even, and negative numbers follow the same rule as positives.Approach 1: simple loop
Test the remainder of division by 2. A number that divides evenly by 2 leaves remainder 0 — that is the definition of even, and % gives you the remainder directly.
n = 7
if n % 2 == 0:
print("Even")
else:
print("Odd")
# Output: OddThe condition reads like the maths: "if the remainder of n divided by 2 equals 0". Everything else is printing the answer.
Approach 2: reusable function
Wrap the test in a function that returns a boolean. The program then reads as a question and an answer, and the same function works for any list of numbers.
def is_even(n):
return n % 2 == 0
print(is_even(10)) # True
print(is_even(7)) # False
print(is_even(0)) # True
print(is_even(-3)) # FalseReturning True/False instead of printing inside the function keeps the decision reusable — the caller decides what to do with it.
Approach 3: Pythonic alternative
Python lets you pick a value with a conditional expression, which is handy when the output itself must be a word. The bitwise test n & 1 is the compact alternative — it checks the last binary digit.
for n in [4, 7, 0, -3]:
print(n, "Even" if n % 2 == 0 else "Odd")
# Output:
# 4 Even
# 7 Odd
# 0 Even
# -3 OddNote that Python's % behaves politely with negatives: -3 % 2 is 1, so -3 is correctly reported as odd — no special case needed.
Dry run
For input 7: 7 % 2 means "7 divided by 2 leaves what remainder?" — 2 goes into 7 three times (6), remainder 1. Comparing 1 == 0 gives False, so the if branch is skipped and else runs, printing Odd. For 0: 0 % 2 is 0, the comparison is True, and Even prints. Trace every input the same way: remainder first, comparison second, branch third.
Common errors
- Writing
n % 2 = 0— single=assigns; comparison needs==. - Assuming negatives need a special case — in Python they do not:
-3 % 2is1. - Using
input()withoutint():"7" % 2raises a TypeError. - Testing
n / 2 == 0(division) instead ofn % 2 == 0(remainder). - Forgetting that 0 is even — the
elsebranch would mislabel it.
Practice on PyDebug
Turn the idea into a debugging habit with these free browser exercises: