chevron_left
226 points
13 5 3

I. INTRODUCTION

Many newcomers to programming have to do excercises which involve checking if a given input is even or odd. In this article, I will guide you to overcome such exercises. So let’s begin !

In Python, you can use the modulo operator (%) to find the remainder after dividing 2 values.

example = 18 % 2

As you may guess, value of example is 0 because 18 is divisible by 2.

II. APPROACH

As you know, even numbers are numbers like 0, 2, 4, 6, 8, ... and odd number are numbers like 1, 3, 5, 7, 9. You can see that dividing an even number by 2 would have remainder that equals to while dividing an odd number by 2 would produce a remainder whose value is not 0. So we can know if a number is even or odd based on its remainder after dividing it by 2.

First of all, we need to get ther number:

number = input("Please enter a number: )

Then calculate remainder if we divide the number by 2:

remainder = num % 2

Logic for checking if the input is even or odd:

if remainder == 0:
    print("Your number is even")
else:
    print("Your number is odd")

Result:

Please enter a number: 1
Your number is odd
Please enter a number: 6
Your number is even

Here is the completed code:

num = input("Please enter a number: ")
remainder = num % 2
if remainder == 0:
    print("Your number is even")
else:
    print("Your number is odd")

III. CONCLUSION

In this article, I have shown the general way for checking if a given number is even or odd and demonstrated a Python code snippet. I hope knowledge from this article may help you to solve similar problems.

Happy coding !

More Posts

How to check if a number is even or odd in python? Hafsa_Rao - Aug 9
How to check if a number is odd in python offonime - Jun 28
INTRODUCTION TO PYTHON: CONDITIONS IN PYTHON Riya Bisht - Aug 7
How to determine if a number is even or odd in C sakshi - Jun 16
How to use if statement in python amna - Jul 1
A ____________ in a conditional statement checks to see if a statement is true or false in php sakshi - Aug 28
How to find the number of unique elements in list in Python mhfaisal - Jul 14
Javascript checks if the number is even or odd. Farkhanda Athar - Jul 25, 2020
How to check if something is in a dictionary python amna - Jul 25
Number of occurrences of a character in a string in python with example. Tania - Sep 13