  Table of content

## How to check if a number is even or odd in python?

An even number is a number that is divisible by 2 and gives the remainder as 0. An odd number gives remainder as 1 when divided by 2. For example, 2, 4, 6, 8, etc are even numbers whereas 1, 3, 7, 9, etc are odd numbers.

### Checking if a number is even or odd by using the Modulus(%) operator

Consider a user-defined function even_odd that checks if a number is even or odd. The number is passed as a parameter to the even_odd() function. The modulus (%) operator checks if the number is divisible by 2. If the remainder is 0, the number is even. If the remainder is 1, the number is odd.

``````def even_odd(num):
if num%2 ==0:
print(num,"is even")
else:
print(num, "is odd")

even_odd(18)
even_odd(15)``````

The above code returns the output as

``````18 is even
15 is odd``````

### Checking if a number is even or odd by using while loop

Let us consider a number num = 36. A while loop iterates till the value of num is greater than or equal to 2. In every iteration, the value of num is decremented by 2. If the value of num is reduced to 1, then the number is odd. If the value of num is reduced to 0, the number is even.

``````num =36
while(num >= 2):
num -= 2
if num == 0:
print(36, "is even")
else:
print(36, "is odd")``````

The above code gives output as

``36 is even``

### Checking if a number is even or odd by using the bin() function

Consider a user-defined function even_odd that checks if a number is even or odd. The number is passed as a parameter to the even_odd() function. The bin() function converts the number to a binary number and returns the binary number as a string. If the last bit of the number is '1', the number is odd else the number is even.

``````def even_odd(num):

binary = bin(num)
print("Binary of", num, "is:", binary)
if binary[-1] == '1':
print(num, "is odd")
else:
print(num, "is even")

even_odd(18)
even_odd(15)``````

The above code returns the output as

``````Binary of 18 is: 0b10010
18 is even
Binary of 15 is: 0b1111
15 is odd``````

### Checking if a number is even or odd by using the bitwise & operator

If the last bit of the integer is 1, the number is odd. If the last bit is 0, the number is even. The last bit can be determined by performing the bitwise (&) operation between the given integer and integer 1. The bitwise & compares each bit of the two integers and returns 1 if both bits are 1 else 0. The result is returned in integer data type. Consider a number the 7. The bitwise operation of 7 and 1 returns the output as integer 1 (In binary=00000001). The last bit is 1, Hence the number is odd.

``````num = 7
if (num & 1) == 1:
print(num, "is odd")
else:
print(num, "is even")``````

The above code gives output as

``7 is odd``

For an even number, the bitwise & operation with a given integer value and 1 returns integer value as 0.

0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions