Python Program to Check if a Number Is Even or Odd
Beginner Numbers
Checks whether a number is even or odd with the % operator, which gives the remainder after dividing by 2.
A whole number is even when 2 divides it exactly and odd when that leaves a remainder of 1. 10 is even
(10 ÷ 2 = 5, remainder 0) and 7 is odd (7 ÷ 2 = 3, remainder 1). Python's remainder operator
% gives that remainder, so the whole check is one comparison.
Program
def even_or_odd(number):
"""'even' if 2 divides number exactly, otherwise 'odd'."""
if number % 2 == 0:
return "even"
return "odd"
print("10 is", even_or_odd(10))
print("7 is", even_or_odd(7))
Open in the editor Download even_odd.py
Output
10 is even
7 is odd
How it works
Step through the program line by line: each step below shows up as its line runs.
-
number % 2is the remainder after dividing by 2:10 % 2is 0 and7 % 2is 1. Every whole number leaves 0 or 1, so this one test sorts them all.==compares two values; a single=would be an error here. - A remainder of 0 means 2 goes into the number exactly, so it's even.
returnhands back the answer and ends the function there. - The function reaches this line only when the remainder was 1, so the number is odd. It needs no
else: for an even number, thereturnabove has already left the function. - The program checks 10, which is even, and 7, which is odd.
Other ways to write it
With a conditional expression
An if and else that only pick between two values fit on one line as a conditional expression:
def even_or_odd(number):
return "even" if number % 2 == 0 else "odd"
print(even_or_odd(12), even_or_odd(15))By the last digit
The rule from school works too: a number is even when its last digit is 0, 2, 4, 6 or 8. str(number)[-1] is that
last digit, as text.
def even_or_odd(number):
if str(number)[-1] in "02468":
return "even"
return "odd"
print(even_or_odd(348), even_or_odd(1001))Try it yourself
- Check 0 and negative numbers such as -7 and -10. In Python
-7 % 2is 1, so the function still gets them right. - Write
is_even(number), which returnsTrueorFalseinstead, and printis_even(10). - Print the even numbers from 1 to 20 with a
forloop and the function. - Count the odd numbers in a list such as
[3, 8, 11, 14, 20]: there are two.