Python, how to check if a number is odd or even

By

Learn how to check if a number is odd or even in Python with the modulo operator, testing if n % 2 equals 0, and filtering a list of numbers with filter().

~~~

To check if a number is odd or even in Python, use the modulo operator %. If num % 2 equals 0, the number is even. Otherwise it’s odd.

Why does this work? A number is even when divided by 2 the remainder is 0. Think 2, 4, 10, 200.000.

Odd numbers generate a remainder of 1: 1, 3, 5, 15…

The % operator gives you exactly that remainder. 10 % 2 is 0, 15 % 2 is 1.

You can check if a number is even or odd with an if conditional:

num = 3
if (num % 2) == 0:
   print('even')
else:
   print('odd')

This prints odd.

If you need the check in more than one place, wrap it in a small function that returns a boolean:

def is_even(num):
    return num % 2 == 0

print(is_even(10)) # True
print(is_even(7)) # False

The comparison already evaluates to True or False, so there’s nothing else to write.

What about negative numbers?

In Python, % always returns a non-negative result when the divisor is positive:

print(-3 % 2) # 1
print(-4 % 2) # 0

So both num % 2 == 0 and num % 2 == 1 keep working for negatives. Some other languages return -1 for -3 % 2, so this is a nice Python property. If you write the odd check as num % 2 != 0, it works everywhere.

Filtering a list of numbers

If you have an array of numbers and want to get the ones even or odd, you can use filter() with a lambda function:

numbers = [1, 2, 3]

even = filter(lambda n: n % 2 == 0, numbers)
odd = filter(lambda n: n % 2 == 1, numbers)

print(list(even)) # [2]
print(list(odd)) # [1, 3]

Notice that filter() returns a lazy filter object, not a list. That’s why we wrap it in list() to print it. And a filter object can only be consumed once: calling list(even) a second time gives you an empty list.

Alternatively, you can use a list comprehension, which returns a real list right away:

even = [n for n in numbers if n % 2 == 0]

A common pitfall

If the number comes from user input, remember that input() returns a string:

num = input('Enter a number: ')
print(num % 2) # TypeError: not all arguments converted during string formatting

Convert it to an integer first with int(num), and the check works as expected.

Tagged: Python · All topics
~~~

Related posts about python: