DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Day 22: Python Even-Odd Counter – Count Even and Odd Integers in a List with Type Checks

Welcome to Day 22 of the #80DaysOfChallenges journey! Today’s beginner-level task focuses on building a function to count even and odd numbers in a list, while adding type validation to catch non-integers like floats. This exercise sharpens your skills in loops, conditionals, error handling, and basic data validation, core elements for processing collections in Python. If you're starting out or revisiting fundamentals, this "Python count even odd" guide demonstrates how to combine checks and counts into a reliable utility with straightforward messaging.


💡 Key Takeaways from Day 22: Even-Odd Counting Function

This challenge creates a function that processes a list of numbers, tallies even and odd integers, and throws an error for any floats detected. It’s a solid intro to defensive programming, ensuring inputs meet expectations before proceeding. We’ll cover the essentials: function structure with error raising, type validation, and loop-based counting with formatted output.

1. Function Design: Input Validation and String Output

The count_even_odd function accepts a list and returns a string message, or raises a ValueError if issues arise. Its signature keeps things explicit:

def count_even_odd(numbers: list) -> str:
    """
    Counts even and odd integers in the list.
    Raises an error if a float is found.
    Returns a user-friendly message.
    """
Enter fullscreen mode Exit fullscreen mode

We initialize counters at the top:

even_count = 0  # initialize even counter
odd_count = 0   # initialize odd counter
Enter fullscreen mode Exit fullscreen mode

This setup emphasizes clarity, no magic numbers, no hidden state. The function is self-contained, processing the list in one pass and formatting the result directly: f"\nIn your list: {even_count} even numbers and {odd_count} odd numbers.\n". It’s designed for easy integration, like in data cleaning scripts, where you want quick feedback without extra parsing.

2. Type Validation: Catching Non-Integers Early

Before counting, we scan for floats using isinstance:

for num in numbers:
    # Check if the number is a float
    if isinstance(num, float):
        raise ValueError(f"Error: Found a float value ({num}). Please provide only integers.\n")
Enter fullscreen mode Exit fullscreen mode

This halts execution on invalid types, preventing subtle bugs downstream. It’s a practical way to enforce integers-only input, common in numeric tasks. The error message includes the offending value for quick debugging, turning a potential headache into something actionable.

3. Counting Logic: Modulo Checks and Example Usage

The core loop handles the even-odd split with modulo:

# Count even or odd
if num % 2 == 0:
    even_count += 1
else:
    odd_count += 1
Enter fullscreen mode Exit fullscreen mode

It’s simple and efficient, % 2 is a standard check for parity. Wrap it in a try-except for real-world use:

try:
    my_list = [10, 21, 4, 45, 66, 93, 0]  # example list with integers
    message = count_even_odd(my_list)
    print(message)
except ValueError as ve:
    # Print error message in a clear format
    print(f"\n[ERROR] {ve}")
Enter fullscreen mode Exit fullscreen mode

For [10, 21, 4, 45, 66, 93, 0], it outputs: \nIn your list: 4 even numbers and 3 odd numbers.\n. If a float sneaks in, like [1, 2.5], you get: [ERROR] Error: Found a float value (2.5). Please provide only integers.. This flow keeps the code robust and user-aware.


🎯 Summary and Reflections

This even-odd counter highlights how adding validation elevates a basic loop into something more reliable. It reinforced for me:

  • Defensive coding: Early checks like isinstance save time on bad data.
  • Error handling: Raising and catching ValueError makes failures informative.
  • Output focus: Returning strings simplifies integration for scripts or apps.

What stood out was how type safety turns a toy example into a tool you’d actually use. For tweaks, consider expanding to count zeros separately or handling empty lists gracefully.

Advanced Alternatives: Switch to a dictionary for counts (counts = {'even': 0, 'odd': 0}), or use list comprehensions: even = len([n for n in numbers if n % 2 == 0 and isinstance(n, int)]). How do you validate lists in Python? Drop your approach in the comments!


🚀 Next Steps and Resources

Day 22 built on loop basics with a layer of validation, prepping for more data-heavy challenges ahead. If you're following #80DaysOfChallenges, how did you modify the error handling? Show your code!

Top comments (0)