python program to check input number is odd or even

Python Program to Check Given Number is Odd or Even

This tutorial guides you on how to write python program to check given number is odd or even.

Python Program to Check Given Number is Odd or Even

To understand this example program, you should be aware of Python programming basics like Python if else statement and Python operators.

We are going to use Python if else and Python modulo operator in our example. The symbol “%” is called Modulo Operator in most of the programming languages including Python.

The modulo operator returns the remainder of dividing the left hand operand by the right hand operand. Therefore, you can simply say it returns the remainder of a division.

For example, the following program let you to enter any number and check whether the input number is odd or even. If the remainder is 1 then the given number is odd number. And when the number is perfectly divisible by 2 and the gives remainder 0, then it is even number.

Example – Check Number is Odd or Even

n = int(input("Enter any number: "))
if (n % 2) == 0:
   print("{0} is Even".format(n))
else:
   print("{0} is Odd".format(n))

Output 1:

Enter any number: 10

10 is Even

Output 2:

Enter any number: 13

13 is Odd

Note, if you don’t provide the proper input, then you will get invalid literal for int() with base 10 error as shown below. Therefore, make sure that you provide valid input.

Enter any number: asf
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-134-c041f0854060> in <module>
----> 1 n = int(input("Enter any number: "))
      2 if (n % 2) == 0:
      3    print("{0} is Even".format(n))
      4 else:
      5    print("{0} is Odd".format(n))

ValueError: invalid literal for int() with base 10: 'asf'

Below is the screenshot of the same executed in Python Jupyter Notebook for your reference.
python program to check input number is odd or even
That’s it. Hope it helped πŸ™‚

You’ll also like:

References

Β 

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments