Open In App

Python Program to Check if a Number is Odd or Even

Last Updated : 27 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Even Numbers are exactly divisible by 2 and Odd Numbers are not exactly divisible by 2. We can use modulo operator (%) to check if the number is even or odd. For even numbers, the remainder when divided by 2 is 0, and for odd numbers, the remainder is 1.

In this article, we will learn how to check if given number is Even or Odd using Python.

x = 24 
# Check the remainder dividing x by 2 is 0
if x % 2 == 0:
    print("Even")
else:
    print("Odd")

# Checking another number    
x = 7

if x % 2 == 0:

  print("Even")
else:
    print("Odd")

Output
Even
Odd

Use lambda with map [Memory Efficient]

We have defined same as above logic with lambda and applied this to every list element using map

a = [1, 2, 3, 4, 5]

res = map(lambda num: str(num) + " Even" 
          if num % 2 == 0 else str(num) + " Odd", a)

print("\n".join(res))

Output
1 Odd
2 Even
3 Odd
4 Even
5 Odd

Note: Using map is more memory-efficient because it creates an iterator instead of creating an entire list in memory.


Using Bitwise And(&) Operator

Another way to check whether a number is even or odd is by using the bitwise AND operator (&). In binary representation. Bitwise AND (&) operator gives 1 only for (1&1) otherwise it gives 0. So, knowing this we are going to evaluate the bitwise AND of a number with 1 and if the result is 1 number is odd, and if it is 0 number is even.

x = 24

# If the least significant bit is 0
# the number is even otherwise, it's odd
if x & 1 == 0:
    print("Even")
else:
    print("Odd")   
    

# Checking another number
x = 7

if x & 1 == 0:
    print("Even")
else:
    print("Odd")   

Output
Even
Odd



Next Article

Similar Reads

three90RightbarBannerImg