In this Python example, we will discuss the ways to check if any given number is even or odd. Let’s begin.
1. What are Even or Odd numbers?
An even number is defined as a number that can be divided by two giving zero remainder or can be divided into two equal groups. On the other hand, an odd number is defined as a number that cannot be divided by two or cannot be divided into two equal groups– Cuemath
Input : 4
Output : Even Number
Explanation : 4 % 2 is 0. Hence Even
Input : 9
Output : Odd Number
Explanation : 9 % 2 is not 0. Hence Odd
Some of the topics which will be helpful for understanding the program implementation better are:
Let’s find out, how can we find the number is even or odd using Python.
2. Check if Any Number is Even or Odd using Subtraction
- In this method, we will subtract the given number by number-2
- If we get the last number after subtraction as 0, then the number is even
- If we get the last number after subtraction as 1, then the number is odd
NOTE: This method cannot be applied to float numbers. The method can only work for integer numbers.
Let’s implement the code and see how it works.
# Python Program to Check is Number is even or odd using subtraction
if n == 0:
elif n == 1:
num = int(input("Enter a integer number: "))
print("Given number is even")
print("Given number is odd")
Enter a integer number: 67
Given number is odd
In the above program, we have created a function
check() which will take the number which the user will provide. Inside the function, the number will be checked with the conditions and when the number will be subtracted, it will be called using
3. Check if Any Number is Even or Odd using Modulus Operator
In this method, we take the help of the modulus operator to find the given number is even or odd. Modulo operator gives the remainder.
This is the preferred way to check whether a number is even or odd.
Let’s implement and find out the working of the code.
# Python Program to Check is Number is even or odd using Modulo
if num % 2 == 0:
return "The Given Number is Even Number"
return "The Given Number is Odd Number"
num = 3
The Given Number is Odd Number
In the above program, we have made a function in which we have given the if…else… condition that if
num % 2 == 0 then the given number is even. Else the given number is odd.
In this article, we have learned how can we check if any given number is even or odd. We have used two different techniques for the implementation, one using the subtraction method and other using the modulo operator method.
Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.
Also for examples in Python and practice please refer to Python Examples.
Complete code samples are present on Github project.
An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding
Do not forget to share and Subscribe.
Happy coding!! 😊