Home ยป Check if a Number is Odd or Even in python

Check if a Number is Odd or Even in python

Java SE 11 Programmer II [1Z0-816] Practice Tests
Oracle Java Certification
1 Year Subscription
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]
Spring Framework Basics Video Course

In this article we look at whether a number is odd or even.

There is a fairly simple formula to work this out –

If you divide a number by 2 and it gives a remainder of 0 then it is known as even number, otherwise it is an odd number.

Code examples

Example 1 – odd or even

We will take input from the user and display whether its odd or even

number = int(input(" Please Enter any Integer Value : "))

if(number % 2 == 0):
    print("{0} is an Even Number".format(number))
else:
    print("{0} is an Odd Number".format(number))

A couple of runs

>>> %Run oddeven.py
Please Enter any Integer Value : 11
11 is an Odd Number
>>> %Run oddeven.py
Please Enter any Integer Value : 8
8 is an Even Number

Example 2 – even numbers in a range

We will take input from the user and display whether its an even number in a range

In this example we use a while loop, you can quite easily use a for loop as well

# Print Even Numbers from minimum to maximum
minimum = int(input(" Please Enter the Minimum Value : "))
maximum = int(input(" Please Enter the Maximum Value : "))

for number in range(minimum, maximum+1):
    if(number % 2 == 0):
        print("{0}".format(number))

Here is a run of this

>>> %Run evennumbers.py
 Please Enter the Minimum Value : 2
 Please Enter the Maximum Value : 13
2
4
6
8
10
12

Example 3 – odd numbers in a range

We will take input from the user and display whether its an odd number in a range

In this example we use a while loop, you can quite easily use a for loop as well

The change is that we now check whether the remainder of the user inputted number divided by 2 is not equal to 0

# Print Odd Numbers from minimum to maximum
minimum = int(input(" Please Enter the Minimum Value : "))
maximum = int(input(" Please Enter the Maximum Value : "))

for number in range(minimum, maximum+1):
    if(number % 2 != 0):
        print("{0}".format(number))

Here is a run of this

>>> %Run oddnumbers.py
 Please Enter the Minimum Value : 2
 Please Enter the Maximum Value : 10
3
5
7
9

Links

You can see these examples on github at the link below

https://github.com/programmershelp/maxpython/tree/main/code%20example/oddeven

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More