How can you tell if a number is odd or even in Python?
The easiest way to determine if a number is even or odd in Python is to use the
modulus operator
. This operator, denoted as the percentage sign
%
displays the
remainder
from a division operation. To determine if a number is even simply apply
my_number % 2 == 0
where
my_number
is your number and if this result is
True
then your number is even, otherwise, it is odd.
Here’s a simple example demonstrating how this works:
>>> im_even = 6
>>> im_even % 2 == 0
True
>>> im_odd = 5
>>> im_odd % 2 == 0
False
isodd
&
iseven
Functions
From this understanding you can even create your own
isodd
or
iseven
function depending on how often you need to perform this comparison in your code.
An example of your own
isodd
or
iseven
function could look something like this:
def iseven(n):
return n % 2 == 0
def isodd(n):
return n % 2 == 1
As you can see from the two functions above there is a slight difference in each where if the result of the modulo operation produces a zero for the
iseven
function then you know the number is even, whereas for the
isodd
function compares the modulo result to 1.
Both results from the functions would return
True
if the number inserted into the parameter satisfies the conditions.
Here is an example of the output when applying these functions:
>>> iseven(6)
True
>>> isodd(5)
True
>>> iseven(7)
False
>>> isodd(8)
False
As you can see the operation is a little tidier and should make clear sense to anybody reading your code.
Summary
The modulus operator is another arithmetic operator available in Python and can help in determining whether a number is odd or even. Using the modulus operator with the number 2 will help to show if there is a remainder or not with any number.
The result from the operation
my_number % 2
will either produce a 0 or 1, with 0 implying the number is even – as all even numbers can be divided by 2, and 1 implying the number is odd.
You can also wrap this modulo operation into your own custom functions
isodd
and
iseven
by extending it with a comparison to 0 or 1. This might help make your code more easy to read.