In this example, you will learn to check the number even or odd using three different methods.
Example 1: Using the modulus operator
This method checks if the remainder of the number divided by 2 is 0 or not. If it is 0, then the number is even; otherwise, it is odd. The ternary operator is used here to print “Even” if the condition is true and “Odd” if it is false
n = 250
print("Even" if n % 2 == 0 else "Odd")
Output
Even
Example 2: Using bitwise AND operator
This method uses a bitwise AND operator with 1 to check whether the last bit of the number is 0 or 1. If it is 0, then the number is even; otherwise, it is odd. The ternary operator is used here to print “Even” if the condition is true and “Odd” if it is false.
n = 11
print("Even" if n & 1 == 0 else "Odd")
Output
Odd
Using divmod
function
In this example we use the divmod() function which takes two arguments, the first is the number and the second is the divisor.
It returns a tuple with the quotient and remainder. We only need to check if the remainder is 0 or not. If it is 0, then the number is even; otherwise, it is odd. The ternary operator is used here to print “Even” if the condition is true and “Odd” if it is false.
n = 12
print("Even" if divmod(n, 2)[1] == 0 else "Odd")
Output
Even
In Python, there are different ways to check whether a number is even or odd such as using modulus operator, bitwise AND operator, or divmod function