Check Even or Odd in Python
Decide whether an integer is even or odd with one Python remainder test. This first conditional exercise includes zero, negatives, and readable comparisons.
1# Program to check if a number is even or odd23num = int(input("Enter an integer: "))45if num % 2 == 0:6 print(num, "is even")7else:8 print(num, "is odd")
Sample Output
7 is odd
7 % 2 is 1, so only the odd message is displayed.
In this one
- Use modulo to test divisibility
- Write a two-way if/else
- Include zero and negative integers
How it works
- 1
Convert the input to an integer named num.
- 2
Evaluate num % 2 == 0.
- 3
Print the even message on a zero remainder, otherwise the odd message.
Edge cases
Zero
Enter 0.
The remainder is zero, so the program correctly prints even.
Decimal text
Enter 7.5.
int cannot parse that response as an integer and raises ValueError.
What's going on
Even means divisible by 2. % gives the remainder, so num % 2 == 0 asks whether division by 2 leaves nothing over. 7 leaves 1; 8 leaves 0.
int converts the response before the test. The if branch prints even and the else branch prints odd. Exactly one branch runs. = assigns a value; == compares values, and this condition needs comparison.
Negative numbers work too: -3 % 2 is 1 in Python, so -3 is odd. Zero is even because 0 % 2 is 0. You may see if num % 2 used to test oddness through truthiness. It works, but spelling out the comparison makes your intention easier to mark and easier to debug.
After this program
If the idea is still fuzzy, read Day 1: Introduction to Python in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 basic python programs, or see every topic on Python exercises.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What remainder identifies an even integer?
Pick an answer to check it.
Question 2
Is -3 odd in this program?
Pick an answer to check it.
Questions people ask
What remainder identifies an even integer?
Zero, because an even integer is divisible by 2 without a remainder.
Is -3 odd in this program?
Yes. -3 % 2 is 1, so it goes to the odd branch.
Why not use a single = in the condition?
A single = is assignment syntax, while == checks whether two values are equal.