Python Program to Check number is even or odd

In this program, we will find whether a given number is even or odd. We have discussed two methods of finding it.

So, firstly we take a number from the user, using the built-in input() function and typecast the return value from input() function into int datatype.

We have used the modulus operator(%) which will give the remainder after dividing the number with 2. And then using the if- else statement we check whether the number is even or odd.

Code :

# taking an input
num = int(input("Enter a number: "))    

# checking the number
if num%2 == 0:                          
    print(num," is an even number.")   
else:
    print(num," is an odd number.")

Output:-

Enter a number: 45
45 is an odd number.

Let's discuss the other method.


Checking a number is odd or even using the bitwise operator

In this method, we will use the AND(&) bitwise operator. This operator is used to AND the bits of the number with the bits of another number.

So, here we will AND the Least Significant Bit(LSB) of the given number with bit 1.

We know that if a number is odd then it's LSB will be 1 and if it is even then LSB will be 0. Hence, using AND with an odd number will give 1 which will be considered as True otherwise against an even number it will give 0 which will be considered as False. And we can use these outcomes in the if-else statements.

Code :

# taking an input
num = int(input("Enter a number: "))    

# checking the number using bitwise operator
if num&1:                          
    print(num,"is an odd number.")    
else:
    print(num,"is an even number.")

Output:-

Enter a number: 45
45 is an odd number.

Now you know both the ways of finding the odd or even number.

Now you can use the if-else statement and bitwise operators to make other programs.







The following two tabs change content below.
Amit Rawat

Amit Rawat

Founder and Developer at SpiderLabWeb
I love to work on new projects and also work on my ideas. My main field of interest is Web Development.

You may also like...