Summarise With AI
Back

Even Odd Program in Python with Examples

10 Jan 2025
5 min read

What This Blog Covers

  • Explains what even and odd numbers are using simple logic and examples
  • Shows multiple ways to write an even-odd program in Python
  • Covers modulus (%), bitwise AND (&), functions, ternary operator, and list-based approaches
  • Explains user input handling and common mistakes to avoid
  • Discusses performance differences and real-world applications of even–odd checks

Introduction

Almost every beginner’s coding journey starts with a simple question: Is this number even or odd? Writing an even odd program in Python develops a solid foundation in conditions, operators, and logical reasoning, despite its seemingly simple appearance. Interviews, competitive programming, and real-world logic like turn-based systems and data filtering all regularly use this idea.

This blog will teach you about how to check even and odd integers in Python in a variety of ways, from simple methods for beginners to sophisticated strategies like bitwise operations. Every technique is described with examples, performance comparisons, and real-world applications so that you understand not only how it functions but also why it should be used.

What Makes a Number Even or Odd?

If a number can be divided by two without leaving a remainder, it is even. Put another way, there is nothing left over after dividing the number by two. On the other hand, if a number has a remainder of 1 after being divided by 2, it is odd.

The Role of the Modulus Operator (%)

In Python, the modulus operator (%) is used to calculate the remainder after division. This operator is central to the logic for checking evenness or oddness:

  • If num % 2 == 0, the number is even.
  • If num % 2 == 1, the number is odd.

This works for both positive and negative integers, as well as zero.

Step-by-Step Example

Let's see how this logic works with a few examples:

Number Calculation Remainder Even/Odd 4 4 % 2 0 Even 7 7 % 2 1 Odd 0 0 % 2 0 Even -3 -3 % 2 1 Odd

  • When you perform num % 2, Python returns the remainder after dividing num by 2.
  • If the remainder is 0, the number is evenly divisible by 2 (even).
  • If the remainder is 1, the number is not evenly divisible by 2 (odd).

Why Does This Logic Work?

  • Even numbers can always be written as 2k, where k is an integer. Dividing 2k by 2 leaves no remainder.
  • One way to express odd numbers is as 2k + 1. Dividing this by 2 always leaves a remainder of 1.

Alternative Approach: Bitwise AND Operator

Besides the modulus operator, Python also allows you to use the bitwise AND operator (&) to check for evenness or oddness:

  • num & 1 == 0 means the number is even.
  • num & 1 == 1 means the number is odd.

This is effective because even binary numbers always finish with a 0 (the least important bit), while odd binary numbers always end with a 1.

Summary

  • Modulus operator (%): Verifies the amount left over after dividing by two.
  • Even numbers: num % 2 == 0
  • Odd numbers: num % 2 == 1
  • All integers, including zero and negatives, are covered by the reasoning.
  • Bitwise AND (&): An efficient alternative, especially for performance-critical code.

By understanding and applying this logic, you can reliably determine whether any integer in Python is even or odd.

Methods to Check Even Odd program in Python

In Python, we can verify whether a number is even or odd using various techniques. Here are some commonly used methods to check even odd program in Python:

Method 1: Using the Modulus Operator (%)

The most popular and simple method for figuring out if an integer is even or odd is to use the modulus operator (%). When two numbers are divided, the modulus operator yields the residual.

Code Implementation

# Taking input from the user
num = int(input("Enter a number: "))

# Checking if the number is even or odd using the modulus operator
if num % 2 == 0:
    print(f"{num} is Even")
else:
    print(f"{num} is Odd")

Output:

Enter a number: 8
8 is Even

Explanation of the Code

1. Taking User Input:

num = int(input("Enter a number: "))

The input() function takes user input as a string. It may be utilized for numerical computations by converting the value to an integer using the int() method.

2. Checking Even or Odd:

if num % 2 == 0:

When num is divided by two, the modulus operator (%) determines the remainder. The number is even if the remainder is zero. The number is odd if the remainder is 1.

3. Printing the Result:

print(f"{num} is Even")

It prints that the number is even if the condition (num % 2 == 0) is true. If not, it indicates that the number is odd.

Method 2: Using a Function

Encapsulating the logic inside a function improves code reusability, modularity, and readability. Instead of writing the even odd program in Python, in different parts of the program, we define a function that can be reused whenever needed.

Code Implementation

# Defining a function to check even or odd
def check_even_odd(num):
    if num % 2 == 0:
        return f"{num} is Even"
    else:
        return f"{num} is Odd"

# Taking user input
number = int(input("Enter a number: "))

# Calling the function and printing the result
print(check_even_odd(number))

Output:

Enter a number: 10
10 is Even

Explanation of the Code

1. Defining a Function (check_even_odd):

def check_even_odd(num):

The function check_even_odd() takes one parameter, num, which represents the number we want to check.

2. Checking Even or Odd Using % Operator:

if num % 2 == 0:

If the remainder when dividing num by 2 is 0, the number is even. Otherwise, the number is odd.

3. Returning the Result:

return f"{num} is Even"

The function returns a formatted string indicating whether the number is even or odd.

4. Taking User Input and Calling the Function:

number = int(input("Enter a number: "))
print(check_even_odd(number))

The user enters an integer into the program's code. The function check_even_odd(number) is called, and the returned value is printed.

Method 3: Using the Ternary Operator

The ternary operator in Python is a shorthand way of writing an if-else statement in a single line. This improves the code's readability and conciseness, particularly for basic conditions like determining if a number is even or odd. Here is the even odd program in Python using the Ternary Operator:

Code Implementation

# Taking input from the user
num = int(input("Enter a number: "))

# Checking if something is even or odd using the ternary operator
result = f"{num} is Even" if num % 2 == 0 else f"{num} is Odd"

# Printing the result
print(result)

Output:

Enter a number: 12
12 is Even

Explanation of the Code

1. Taking User Input:

num = int(input("Enter a number: "))

The user is asked to input a number by the application. The input is converted from a string by the input() function to an integer by the int() function.

2. Using the Ternary Operator:

result = f"{num} is Even" if num % 2 == 0 else f"{num} is Odd"

Here, if num % 2 == 0 is True, "num is Even" is assigned to the result. Otherwise, "num is Odd" is assigned to the result.

3. Printing the Result:

print(result)

The program prints whether the number is even or odd.

Method 4: Using the Bitwise AND Operator (&)

The bitwise AND operator (&) is a powerful method to check if a number is even or odd. It works based on the least significant bit (LSB) in the binary representation of numbers. 

  • Even numbers always have their LSB as 0.
  • Odd numbers always have their LSB as 1.
  • Performing num & 1 checks the LSB. 
  • If the result is 0, the number is even. 
  • If the result is 1, the number is odd.

Here’s the even odd program in Python using the Bitwise AND Operator (&).

Code Implementation

# Taking input from the user
num = int(input("Enter a number: "))

# Using bitwise AND operator to check even or odd
if num & 1 == 0:
    print(f"{num} is Even")
else:
    print(f"{num} is Odd")

Output:

Enter a number: 8
8 is Even

Explanation of the Code

1. Taking User Input:

num = int(input("Enter a number: "))

The user enters a number, which is converted to an integer.

2. Checking Even or Odd Using Bitwise AND:

if num & 1 == 0:
  • A bitwise AND operation between num and 1 is carried out by num & 1.
  • Since num's last bit (LSB) is 0 if num is even, num & 1 equals 0.
  • The last bit (LSB) of an odd number is 1, therefore num & 1 equals 1.

3. Printing the Result:

print(f"{num} is Even")  

If the result is 0, the number is even. Otherwise, it prints odd.

Why Does This Work?

The bitwise AND operation works because of how binary numbers represent even and odd values:

Decimal Binary num & 1 Result
0 0000 0 Even
1 0001 1 Odd
2 0010 0 Even
3 0011 1 Odd
4 0100 0 Even
5 0101 1 Odd

Checking Multiple Numbers (List of Numbers)

Instead of checking a single number, we can check whether multiple numbers in a list are even or odd. One efficient way to do this is list comprehension, which allows for concise and readable code. Here’s the code for even odd program in Python to check multiple Numbers (List of Numbers):

Code Implementation (Using List Comprehension)

# List of numbers to check
numbers = [10, 15, 22, 31, 40, 55, 68, 73]

# Using list comprehension to check even or odd
results = [f"{num} is Even" if num % 2 == 0 else f"{num} is Odd" for num in numbers]

# Printing the results
for result in results:
    print(result)

Output:

10 is Even
15 is Odd
22 is Even
31 is Odd
40 is Even
55 is Odd
68 is Even
73 is Odd

Explanation of the Code

1. Defining a List of Numbers:

numbers = [10, 15, 22, 31, 40, 55, 68, 73]

We define a list containing multiple numbers to check.

2. Using List Comprehension to Determine Even/Odd:

results = [f"{num} is Even" if num % 2 == 0 else f"{num} is Odd" for num in numbers]

This is a compact way to iterate over the list and check each number. The ternary operator f"{num} is Even" if num % 2 == 0 else f"{num} is Odd" is applied to every element in the list.

3. Printing the Results:

for result in results:
    print(result)

The results list contains the results. We iterate over the results and print each statement.

Alternative Approach: Using a Function

We can also define a function to check multiple numbers:

def check_numbers(nums):
    return [f"{num} is Even" if num % 2 == 0 else f"{num} is Odd" for num in nums]

# List of numbers
numbers = [2, 7, 14, 19, 24]

# Calling function and printing results
for result in check_numbers(numbers):
    print(result)

Output:

2 is Even  
7 is Odd  
14 is Even  
19 is Odd  
24 is Even 

Performance Considerations of Different Methods

Method Readability Performance
Modulus (%) High Fast
Bitwise AND (&) Medium Very Fast
Ternary Operator High Fast

User Input Handling in Python (Even–Odd Program)

User input handling is a crucial part of writing interactive Python programs. When checking whether a number is even or odd, the program must first accept a value from the user and convert it into a form that Python can process mathematically.

Taking Input Using the input() Function

Python uses the input() function to read data entered by the user. Whatever the user types is received as a string, even if it looks like a number.

num = input("Enter a number: ")

Here, "Enter a number: " is the user prompt, guiding the user on what to enter, and num is the variable that stores the user’s input.

Converting Input Using int()

Since mathematical operations cannot be performed directly on strings, the input must be converted into an integer using int().

num = int(input("Enter a number: "))

This conversion allows the program to apply arithmetic checks, such as determining if a number is even or odd.

Using Mathematical Operations

Once converted, mathematical operations like the modulus operator (%) can be applied:

if num % 2 == 0:
    print("Even")
else:
    print("Odd")

The modulus operation checks the remainder when dividing by 2, which forms the basis of even–odd logic.

Handling Multiple Inputs with map()

If you want to check multiple numbers at once, Python provides the map() function to convert several inputs efficiently.

numbers = list(map(int, input("Enter numbers separated by space: ").split()))

Here,

  • split() separates the input string into individual values
  • map(int, ...) converts each value to an integer

Using lambda for Quick Input Processing

Compact logic may be accomplished with a lambda function, particularly in basic programs:

check = lambda x: "Even" if x % 2 == 0 else "Odd"
num = int(input("Enter a number: "))
print(check(num))

Although this method is simple, it works best when readability is not given up.

Common Input Handling Mistakes

  • Forgetting to convert input from a string to an integer
  • Not validating user input (entering text instead of numbers)
  • Using unclear user prompts

A safer approach includes error handling:

try:
    num = int(input("Enter a number: "))
    print("Even" if num % 2 == 0 else "Odd")
except ValueError:
    print("Please enter a valid integer."

Why User Input Handling Matters

Proper user input handling ensures:

  • Proper execution of the software
  • Reduced mistakes during runtime
  • Improved user experience
  • Reliable even-odd tests for practical uses

Bottom Line:

Writing dependable even-odd applications and developing solid basic programming abilities need employing input(), int(), map(), and unambiguous prompts when handling user input in Python.

Real-World Applications of Checking Even and Odd Numbers

1. Game Development

In multiplayer games, alternating turns between players is a common requirement. For example, in games like chess, tic-tac-toe, or any turn-based game, it's important to determine whose turn it is. This can be done by using even and odd numbers, where:

  • Player 1 can always play on even turns.
  • Player 2 can play on odd turns.

This alternation can be achieved by incrementing a counter with each turn and checking whether it's even or odd to determine which player should take their move.

2. Data Processing

Separating even and odd numbers in a dataset can be helpful for a number of data processing tasks, including pattern analysis and number property-based operations.

For example, you could have to:

  • Filter out even numbers from a dataset for analysis.
  • Group even and odd numbers separately for further processing, such as applying different algorithms to each group.

3. Mathematical Computations

Differentiating between even and odd integers is useful for many mathematical processes, particularly when doing optimizations. For example, certain algorithms, such as those used in prime factorization, factors of large numbers, or number theory, can take advantage of the fact that even numbers have specific properties (divisible by 2) and odd numbers do not.

For instance, the Euclidean algorithm for finding the greatest common divisor (GCD) can be optimized by quickly discarding even numbers, making it more efficient.

Common Mistakes and How to Avoid Them

1. Forgetting to Convert Input to an integer

It's simple to overlook the fact that the input() method by default returns a string when receiving user input. An error will occur if you attempt to utilize arithmetic operations like % on a string.

Mistake:

num = input("Enter a number: ")  # num is a string
if num % 2 == 0:  # Error: num is a string, not an integer
    print(f"{num} is Even")

Fix:
Always convert the input to an integer using int() before performing calculations.

num = int(input("Enter a number: "))  # num is now an integer
if num % 2 == 0:
    print(f"{num} is Even")
else:
    print(f"{num} is Odd")

2. Using if num % 2: Instead of if num % 2 == 1

Although using if num % 2: works, it is less explicit and can make your code harder to understand for others or even yourself when you revisit it later. The condition if num % 2: checks if the remainder of num divided by 2 is non-zero, which is True for odd numbers and False for even numbers. However, explicitly comparing it to 1 makes the intent clearer.

Mistake:

if num % 2:
    print("Odd")
else:
    print("Even")

This works, but it’s less readable because it's not obvious that the check is for odd numbers.

Fix:
It’s better to explicitly compare with 1 for clarity.

if num % 2 == 1:
    print("Odd")
else:
    print("Even")

Conclusion

There are several techniques to determine if a number is even odd in Python. The bitwise operator (&) offers a quicker alternative to the most used modulus operator (%). Gaining an understanding of these various methods enhances your ability to solve problems and gets you ready for more complex programming assignments.

You will learn more about Python and numerical operations by practicing and experimenting with these methods.

Key Points to Remember

  1. A number is even if it is divisible by 2 with no remainder, and odd if it leaves a remainder of 1.
  2. The most accessible and popular way to determine if an integer is even or odd in Python is to use the modulus operator (%).
  3. In situations when efficiency is crucial, the bitwise AND operator (&) is helpful since it is quicker and verifies the final binary bit.
  4. To prevent mistakes, always convert user input to integers before performing arithmetic operations.
  5. Instead of choosing a method just because of its brevity, make your choice based on clarity, reusability, and performance needs.

Frequently Asked Questions

1. What is an even number in Python?

Any positive integer that can be split by two without leaving a residual is an even number. The modulus operator (%) in Python may be used to determine whether an integer is even. For even integers, for instance, num % 2 == 0 will yield True.

2. How do you check if a number is odd in Python?

A number is odd if it leaves a remainder of 1 when divided by 2. You can check for odd numbers in Python using num % 2 != 0. If this condition is true, the number is odd.

3. Can the modulus operator be used for both even and odd numbers?

Yes, the modulus operator (%) is perfect for checking both even and odd numbers. For even numbers, num % 2 == 0 returns True, and for odd numbers, num % 2 != 0 returns True.

4. Why is the bitwise AND (&) operator used to check even or odd numbers?

The bitwise AND operator (&) checks the least significant bit (LSB) of a number. For even numbers, the LSB is 0, and for odd numbers, it is 1. Using num & 1, we can quickly determine whether a number is even or odd.

5. Is using if num % 2: a valid way to check for odd numbers in Python?

Yes, if num % 2 is a shorthand way to check if a number is odd. Since the modulus operator returns 1 for odd numbers and 0 for even numbers, this condition evaluates to True for odd numbers and False for even numbers. However, it’s less explicit than if num % 2 == 1.

6. How do you check multiple numbers for even or odd in Python?

You can check multiple numbers using a loop or list comprehension. For example, using a list comprehension:
results = [f"{num} is Even" if num % 2 == 0 else f"{num} is Odd" for num in numbers].

7. Are there any performance considerations when checking even or odd numbers in Python?

Although bitwise operations are often quicker at the CPU level, both the modulus operator (%) and bitwise AND (&) work well. The bitwise AND operator can be a more effective option if you're working with performance-critical systems, but for the majority of applications, the performance difference is insignificant.

Summarise With Ai
ChatGPT
Perplexity
Claude
Gemini
Gork
ChatGPT
Perplexity
Claude
Gemini
Gork
Chat with us
Chat with us
Talk to career expert