In this program, we are going to make a python program to check even or odd number.
In mathematics, an even number is an integer that is divisible by 2, while an odd number is an integer that is not divisible by 2.
For example, the numbers 2, 4, 6, 8, 10, 12, and 14 are all even, because they can all be divided by 2 with no remainder. The numbers 1, 3, 5, 7, 9, 11, and 13 are all odd, because they cannot be divided by 2 with no remainder.
In programming, you can use the modulo operator (%
) to check if a number is even or odd. For example, you can use the following code to check if a number x
is even or odd:
if x % 2 == 0:
# x is even
else:
# x is odd
Define a function to check if a number is even or odd in Python
# define a function to check if a number is even or odd
def check_even_odd(num):
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
# test the function
check_even_odd(2) # prints "2 is even"
check_even_odd(3) # prints "3 is odd"
check_even_odd(-4) # prints "-4 is even"
In this program, we define a function called check_even_odd
that takes in a number num
as an argument. The function uses the modulo operator %
to check if num
is evenly divisible by 2. If it is, then the number is even and the function prints “num
is even”. If it’s not, then the number is odd and the function prints “num
is odd”.
We then call the check_even_odd
function with different numbers to test it.
Related Post: Prime Number Program in Python using while loop
Video Solution
Python Program to Check Even or Odd Using bit manipulation
Last bit of every odd number is set, so if we perform “&” operation between odd number and 1(whose last bit is set “001”) it comes out to a one otherwise it is zero.
number = int(input("Which number do you want to check? "))
if number&1:
print("This is an odd number.")
else:
print("This is an even number.")
This is all about this post, if you have doubts let me know in the comment section. Please rate well in feedback form. Tell us how can we improve this blog so our website can be more engaging.