Skip to content

Python Numbers: How to Check If a Number Is Odd

Learn how to determine if a number is odd in Python using the modulo operator (%) or bitwise AND (&), including input validation and error handling.

Determining whether an integer is even or odd is a fundamental logic operation in programming. An odd number is an integer that is not exactly divisible by 2; when divided by 2, it leaves a remainder of 1 (e.g., 1, 3, 5, -7).

This guide explains how to use the modulo operator (%) to check for odd numbers, how to handle user input, and how to validate data types to prevent errors.

Method 1: Using the Modulo Operator (Standard)

The standard way to check for parity (even/odd) in Python is using the modulo operator (%). This operator returns the remainder of a division.

  • If number % 2 == 0, the number is Even.
  • If number % 2 != 0 (or == 1), the number is Odd.
number = 7

if number % 2 != 0:
    print(f"{number} is an odd number.")
else:
    print(f"{number} is an even number.")

Output:

7 is an odd number.

Method 2: Using Bitwise AND (Optimized)

For high-performance scenarios or low-level algorithmic tasks, you can use the Bitwise AND operator (&).

In binary representation, all odd numbers have their least significant bit (the rightmost bit) set to 1. Even numbers have it set to 0.

  • 3 in binary is 011 (...1 -> Odd)
  • 4 in binary is 100 (...0 -> Even)
number = 9

if number & 1:
    print(f"{number} is Odd")
else:
    print(f"{number} is Even")

Output:

9 is Odd

Handling User Input and Errors

When accepting input from users via input(), the data comes in as a string. You must convert it to an integer. If the user types text or a float, the program will crash unless handled.

Error Scenario

user_input = "abc"

try:
    if int(user_input) % 2 != 0:
        print("Odd")
except ValueError as e:
    print(f"Error: {e}")

Output:

Error: invalid literal for int() with base 10: 'abc'

Solution: Try-Except Block

Wrap the conversion logic in a try-except block to catch ValueError.

user_input = input("Enter an integer: ")

try:
    number = int(user_input)
    
    if number % 2 != 0:
        print(f"{number} is Odd.")
    else:
        print(f"{number} is Even.")
        
except ValueError:
    print("Invalid input. Please enter a whole number (e.g., 5, 10).")

Conclusion

To check if a number is odd in Python:

  1. Use num % 2 != 0 for the standard, readable approach.
  2. Use num & 1 for a bitwise approach (often slightly faster).
  3. Validate Input: Always use try-except ValueError when converting user strings to integers.
Navigation