In this post, you can find 3 different ways to check if a number is odd or even in Python.
Lets see few examples of checking if number is even or odd in Python:
Modulus Operator (%)
number = 5
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
result:
5 is odd
Note: be careful with floating points. Understanding of odd/even for floating points might differ. Example:
number = 5.54
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
result:
5.54 is odd
Bitwise AND (&)
We can use simple trick to detect odd and even numbers in Python
number = 7
if number & 1:
print(f"{number} is odd")
else:
print(f"{number} is even")
result:
7 is odd
How it works
- check whether the last bit of the number
- if last bit is set then the number is odd
- otherwise even
Example of numbers in binary notation :
bin(7)
-0b111
bin(4)
-0b100
Python - odd or even numbers in a list
To check multiple numbers if they are odd or even in Python we can use list comprehension:
[("even" if x % 2 == 0 else "odd") for x in range(5)]
We will check first five numbers and the result is:
['even', 'odd', 'even', 'odd', 'even']
Pandas - odd or even
Finally to check Pandas column for odd or even numbers we can create function and apply it on the column by:
def is_odd(num):
return num & 1 and True or False
df_t['numbers'].apply(is_odd, axis=1)