This article is all about determining whether a given number is an Even or Odd number in Python. Even numbers are those numbers that are divisible by 2. And, the rest of the numbers that aren’t divisible by 2 are called odd numbers. For example, 154 is an even number. When we divide 154 with 2 then it leaves 0 as the remainder. Whereas, 179 is an odd number. Dividing 179 with 2 leaves the remainder 1.
And, the same concept can be applied while writing a Python program that helps us check whether a given number is even or odd.
Breakdown the problem
Before we proceed, it is important to understand how we are going to approach the problem. So, this is what we will do:
Ask for user input: We would ask the user to input a number first.
Check if the user has entered an integer value. If the user hasn’t provided the same then, ask the user to enter it again.
Use the modulus operator (%) to check whether the number is even or odd. We use the conditional statement if-else here.
Within the if-else statement, use the print() function to display the output.
The program to check for even or odd numbers in Python
while True: try: num = int(input("Enter a number: ")) break except: print("The number entered is not an integer. Please enter the number again.") if num % 2 == 0: print("The number entered is an even number.") else: print("The number entered is an odd number.")
There are multiple ways to solve a problem. We have used try and except block here. The try block mainly checks for errors and the except block handles the errors for us.
So, if the user inputs some value that is not an integer then, it prints a statement mentioning that the user hasn’t entered an integer value. And, this will run the program in a loop till the user enters an integer input.
Thereafter, we use the modulus (%) operator to check if a number is an even or odd number. As already discussed, after dividing the user input by 2, the remainder comes out to be zero then it is an even number. Otherwise, it is an odd number.
Here, we have used the int() function to convert the user input into an integer.
Testing the code
Indentation is important in Python. It mainly indicates a block of code. So, just make sure that you write your code keeping that in consideration. Otherwise, our code wouldn’t work as intended.
Run the program and check it for multiple inputs. Start with a string:
Enter a number: sfgfg
It would return:
The number entered is not an integer. Please enter the number again.
This time around, enter an integer value: 54
It should display:
The number entered is an even number.
We used here a combination of the modulus (%) operator and while loop to determine whether a number is even or odd. We would like to add here that, there are multiple ways to write a program. So, it would be different for all. But, if you understand things have been processed then that helps.
More about Parity: