This article will demonstrate a program to check if the input number is even or odd in python with example, output and explanation.

Even number
Integers which are divisible by 2 are called even numbers such as 2, 4, 42, 68, 1024 etc. These numbers when divided by 2 give a remainder 0.
Odd number
Integers which are not divisible by 2 are called odd numbers such as 3, 7, 9, 35, 87 etc. These numbers when divided by 2 give a remainder other than 0.

For checking if a number is odd or even, make use of modulus operator(%). Modulus operator divides two integers and returns the remainder of division.
Thus, if we use modulus operator with 2 and the number to check, it will give the remainder of division. Based on the remainder, we can easily determine if the number is even or odd using if-else statements.
Python program to check odd or even number based on the above algorithm is given below.

# read number from input
num = int(input("Enter a number\n"))

# compare remainder of division with 0
if num % 2 == 0:
    print('Number is even')
    print('Number is odd')

The program reads an integer as input using input() function. Value read with input() function is in string format.
Since we have to perform arithmetic operations on this value, we need to convert it to an integer. This is done with int() function.

After this, we divide the number by 2 and compare the remainder with 0 using == operator. If the remainder is 0, the input number is even else it is odd. The result is printed on the screen.
Output of the program is

Enter a number
Number is odd

Enter a number
Number is even

Using function
You can place the logic to check if a number is even or odd in a function to make it reusable. The function shall accept the number to test as argument and return True or False based on the function name.
Below is a function to test even odd in python.

def is_even(num):
    # check f remainder is 0 and return result
    return num % 2 == 0

num = int(input("Enter a number\n"))
# test with a function
if is_even(num):
    print('Number is even')
    print('Number is odd')

The function in this example accepts a number and returns True if the remainder after division by 2 is 0 or the number is even and False if the remainder is non-zero or the number is odd.
Based on the value returned by the function, we can output the result.

Do not forget to click the clap if the article was useful.


Share your thoughts !!

Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.