0
0
PythonProgramBeginner · 2 min read

Python Program to Check if Number is Even or Odd

You can check if a number is even or odd in Python by using the modulus operator like this: if number % 2 == 0: means even, else odd.
📋

Examples

Input4
Output4 is even
Input7
Output7 is odd
Input0
Output0 is even
🧠

How to Think About It

To decide if a number is even or odd, think about dividing it by 2. If it divides evenly with no remainder, it is even. If there is a remainder of 1, it is odd. We use the modulus operator % to find the remainder.
📐

Algorithm

1
Get the input number
2
Calculate the remainder when the number is divided by 2
3
If the remainder is 0, the number is even
4
Otherwise, the number is odd
5
Print the result
💻

Code

python
number = int(input('Enter a number: '))
if number % 2 == 0:
    print(f'{number} is even')
else:
    print(f'{number} is odd')
Output
Enter a number: 4 4 is even
🔍

Dry Run

Let's trace the input 7 through the code

1

Input number

User enters 7, so number = 7

2

Calculate remainder

7 % 2 equals 1 (since 7 divided by 2 leaves remainder 1)

3

Check remainder

Since remainder is not 0, the number is odd

4

Print result

Print '7 is odd'

StepOperationValue
1Input number7
27 % 21
3Check if remainder == 0False
4Print output'7 is odd'
💡

Why This Works

Step 1: Using modulus operator

The % operator gives the remainder of division. For even numbers, dividing by 2 leaves remainder 0.

Step 2: Condition check

We check if the remainder is 0 with == 0. If true, number is even; otherwise, odd.

Step 3: Output result

Based on the condition, we print a message telling if the number is even or odd.

🔄

Alternative Approaches

Using bitwise AND operator
python
number = int(input('Enter a number: '))
if number & 1 == 0:
    print(f'{number} is even')
else:
    print(f'{number} is odd')
This method uses bitwise operation which is fast and checks the last binary bit to decide even or odd.
Using a function
python
def is_even(num):
    return num % 2 == 0

number = int(input('Enter a number: '))
if is_even(number):
    print(f'{number} is even')
else:
    print(f'{number} is odd')
This approach wraps the logic in a function for reuse and clarity.

Complexity: O(1) time, O(1) space

Time Complexity

The check uses a single modulus operation and a comparison, both constant time operations.

Space Complexity

Only a few variables are used, so space is constant regardless of input size.

Which Approach is Fastest?

Both modulus and bitwise AND methods run in constant time; bitwise may be slightly faster but difference is negligible for typical use.

ApproachTimeSpaceBest For
Modulus operatorO(1)O(1)Simple and clear code
Bitwise AND operatorO(1)O(1)Slightly faster, uses binary logic
Function wrapperO(1)O(1)Reusable and organized code
💡
Use number % 2 == 0 to quickly check if a number is even in Python.
⚠️
Beginners often forget to convert input to integer, causing errors when using modulus operator.