Categories: Python

How to Check if a Number is Even or Odd with Python

What will you learn?

How to use the modulo operator to check if a number is even or odd with Python.

Step 1: Understand the modulo operator

Most do not know or understand the modulo operator when starting to program, and to be honest, many have been programming for years without discovering the power of the modulo operator.

The modulo operator is the percentage sign (%). What it calculates is the remainder, when dividing a number.

Say, you have 10 USD you need to divide between three people.

Then if you start by giving 1 dollar each, until there is not enough for another round.

The three people will have 3 USD each, and you will have 1 USD left. That 1 USD is the remainder.

Try in Python.

print(10 % 3)

It outputs 1.

Now you understand how modulo works.

Step 2: How to use module to see if number is even or odd

Now assume you have 11 USD and you you have two friends, one called Peter the other Natalie.

Then if you follow the above procedure of giving 1 USD each, until you don’t have enough for another round.

You will have 1 USD left, right?

If you had 122 USD and did the same, then you will have 0 USD left.

Try this experiment a few times and you will see, that for all Even numbers, you will end up with no money. But for all Odd numbers, you will end up with 1 USD at the end.

See, now we have made a way to see if a number is Even or Odd.

Step 3: Python program the can determine if number is Even or Odd

Now we put it all together.

number = int(input("Enter a number: "))

if number % 2 == 0:
    print("Even")
else:
    print("Odd")

Wow. That was amazing.

Rune

Recent Posts

The Best Free Data Science Course Online

Data Science for beginners in this free online course Data Science is over complicated by…

2 months ago

The Ultimate 15 Machine Learning Projects With Source Code

15 Machine Learning Projects That Will Teach You All You Need as Machine Learning Authority…

2 months ago

Learn Python FREE Online

Why learn Python? There are many reasons to learn Python, and that is the power…

2 months ago

The Truth About Being a Python Software Contractor

There are a lot of Myths out there There are lot of Myths about being…

4 months ago

Do This and 10X Your Salary as a Software Engineer

To be honest, I am not really a great programmer - that is not what…

4 months ago

Ultimate Guide to the Data Science Career Path

What does it take to become a Data Scientist? Data Science is in a cross-field…

4 months ago