What does even or odd mean?
A number is called even when it can be divided by 2 with no remainder. Examples of even numbers are 2, 4, 6, 8, 10, and 12.
A number is called odd when it cannot be divided by 2 evenly. In that case, there is a remainder of 1. Examples of odd numbers are 1, 3, 5, 7, 9, and 11.
The key idea: modulo operator
In Python, the modulo operator is written as %. It returns the remainder after division. For example, 10 % 2 returns 0 because 10 is divisible by 2.
So the logic is simple: if a number divided by 2 has a remainder of 0, the number is even. Otherwise, the number is odd.
Rule: number % 2 == 0 means the number is even.
Python code example
The following Python program asks the user to enter a number, converts the input to an integer, and checks whether it is even or odd.
number = int(input("Enter a number: "))
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
How the code works
1. Get input from the user
The input() function receives text from the user. Since input is received as text, we use int() to convert it into a number.
2. Check the remainder
The condition number % 2 == 0 checks whether the remainder is zero after dividing the number by 2.
3. Print the result
If the condition is true, Python prints that the number is even. Otherwise, it prints that the number is odd.
Example outputs
If the user enters 8, the output will be:
Enter a number: 8
The number is even.
If the user enters 5, the output will be:
Enter a number: 5
The number is odd.
Practice challenge
Try improving this program by adding input validation. For example, what should happen if the user enters text instead of a number? This is a good next step for learning error handling in Python.
- Add a try and except block.
- Show a friendly error message when the input is not a valid number.
- Ask the user to try again.
Related pages
You can explore more Python examples and services through the links below.