Python Program - Check whether a Number is Even or Odd
A number is known as an even number if it is a natural number and divisible by 2. On the other hand, an odd number is a natural number which not divisible by 2. Examples:
- Even Number: -10, -4, 0, 6, 18, 50
- Odd Number: -11, -5, -1, 9, 21, 99
Method 1: Using conditional statements
In the example below, the number called MyNum is checked for even number by dividing it by 2 and checking the remainder. For even number, the remainder is 0 and for odd number, the remainder is 1.
MyNum = 17 if MyNum % 2 == 0: print(MyNum,"is an even number.") elif MyNum % 2 == 1: print(MyNum,"is an odd number.")
The above code will give the following output:
17 is an odd number.
Method 2: Using function
In the example below, a function called CheckEven() is created which takes a number as argument and checks it for even number.
def CheckEven(MyNum): if MyNum % 2 == 0: print(MyNum,"is an even number.") elif MyNum % 2 == 1: print(MyNum,"is an odd number.") CheckEven(42)
The above code will give the following output:
42 is an even number.
Method 3: Using bitwise operators
When bitwise operator is used, the last bit of the given number is checked. If the last bit is 1, the number will be odd and if the last bit is 0, the number will be even.
Even Number: 50 -> 110010 & 000001 --------- 000000 Odd Number: 99 -> 1100011 & 0000001 --------- 0000001
def CheckEven(MyNum): if (MyNum & 1): print(MyNum,"is an odd number.") else: print(MyNum,"is an even number.") CheckEven(50) CheckEven(99)
The above code will give the following output:
50 is an even number. 99 is an odd number.
Recommended Pages
- Python Program - To Check Prime Number
- Python Program - Bubble Sort
- Python Program - Selection Sort
- Python Program - Maximum Subarray Sum
- Python Program - Reverse digits of a given Integer
- Python Program - Merge Sort
- Python Program - Shell Sort
- Stack in Python
- Queue in Python
- Python Program - Find LCM of Two Numbers
- Python Program - To Check Whether a Number is Palindrome or Not
- Python Program - To Check Whether a String is Palindrome or Not
- Python Program - Heap Sort
- Python Program - Quick Sort
- Python - Swap Two Numbers without using Temporary Variable
- Python Program - To Check Armstrong Number
- Python Program - Counting Sort
- Python Program - Radix Sort
- Python Program - Find Largest Number among Three Numbers
- Python Program - Print Floyd's Triangle