What You'll Learn
- •Using the modulo operator (%)
- •Understanding even and odd numbers
- •Basic conditional statements (if-else)
- •Type conversion with int()
Python
# Program to check if a number is even or odd
num = int(input("Enter an integer: "))
if num % 2 == 0:
print(num, "is even")
else:
print(num, "is odd")Output
Enter an integer: 7 7 is odd
Check Even or Odd in Python
This program demonstrates how to check if a number is even or odd using the modulo operator.
Understanding Even and Odd Numbers
-
Even numbers: Divisible by 2 (remainder is 0)
- Examples: 2, 4, 6, 8, 10, 12...
-
Odd numbers: Not divisible by 2 (remainder is 1)
- Examples: 1, 3, 5, 7, 9, 11...
Using the Modulo Operator
The modulo operator % returns the remainder of a division:
5 % 2returns1(5 divided by 2 leaves remainder 1)6 % 2returns0(6 divided by 2 leaves remainder 0)
The Logic
pythonif num % 2 == 0: print(num, "is even") else: print(num, "is odd")
How it works:
- If
num % 2 == 0, the number is even - Otherwise, the number is odd
Key Takeaways
1
Modulo operator
% returns the remainder2
Even numbers have remainder 0 when divided by 2
3
Odd numbers have remainder 1 when divided by 2
4
This is a fundamental conditional logic pattern
Step-by-Step Breakdown
- 1Get an integer input from the user.
- 2Use modulo operator to check remainder when divided by 2.
- 3If remainder is 0, the number is even.
- 4Otherwise, the number is odd.
- 5Print the result.