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
- Read the number.
- Work out
n % 2, the remainder after dividing by 2. - 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
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
- Print the result with a one-line conditional expression.
- Test divisibility by other numbers, such as
n % 5 == 0.
Common mistakes
- Writing
n % 2 = 0with a single=, which is a syntax error. - Dividing with
/instead of using%.