Checking if a number is even or odd is one of the most fundamental tasks in programming. An even number is an integer that is divisible by 2 without a remainder (e.g., 2, 4, 6, 0, -2). Conversely, an odd number leaves a remainder of 1 (e.g., 1, 3, 5).
This guide explains how to use the modulo operator % for standard checks and touches on bitwise operations for high-performance scenarios.
Method 1: Using the Modulo Operator (Standard)
The modulo operator % returns the remainder of a division. For any integer n, n % 2 will be 0 if even, and 1 (or -1 in some languages, though Python handles negative modulo consistently as 1) if odd.
Example:
number = 10
if number % 2 == 0:
print(f"{number} is Even")
else:
print(f"{number} is Odd")Output:
10 is EvenHandling Negative Numbers
Python's modulo operator handles negative numbers gracefully for parity checks.
-4 % 2 is 0, so it is correctly identified as even.
Method 2: Using Bitwise AND (Optimized)
For extremely high-performance loops, you can use the bitwise AND operator &. In binary, even numbers always end with a 0 bit (e.g., 2 is 10, 4 is 100), while odd numbers end with a 1 bit.
Performing number & 1 checks only the last bit.
- If
number & 1is0: Even - If
number & 1is1: Odd
number = 7
if (number & 1) == 0:
print(f"{number} is Even")
else:
print(f"{number} is Odd")Output:
7 is OddMethod 3: Checking Floating Point Numbers
The concept of "even" usually applies to integers. However, if you have a float like 4.0, you might want to treat it as even.
A float 4.0 % 2 returns 0.0. A float 4.5 % 2 returns 0.5.
num_float = 4.0
if num_float % 2 == 0:
print(f"{num_float} is effectively even.")
else:
print(f"{num_float} is not even.")Output:
4.0 is effectively even.Common Pitfall: String Inputs
Users input data as strings (e.g., from input()). Performing arithmetic on strings raises a TypeError.
user_input = "10"
try:
if user_input % 2 == 0:
print("Even")
except TypeError as e:
print(f"Error: {e}")
if int(user_input) % 2 == 0:
print("Even (after conversion)")Output:
Error: not all arguments converted during string formatting
Even (after conversion)Conclusion
To check if a number is even:
- Use
num % 2 == 0for the standard, readable approach. - Use
(num & 1) == 0for bitwise operations (advanced). - Convert inputs using
int()before checking to avoid TypeErrors.