YouTip LogoYouTip

Python Even Check

## Python Program to Check If a Number is Even In Python, determining whether an integer is even is a fundamental programming task. An even number is any integer that is exactly divisible by 2, meaning that when divided by 2, the remainder is 0. This tutorial covers the standard approach using the modulo operator (`%`), an alternative performance-optimized approach using bitwise operators, and how to handle edge cases like negative numbers and floats. --- ## 1. The Standard Approach: Modulo Operator (`%`) The most common and readable way to check if a number is even in Python is by using the modulo operator (`%`). The modulo operator returns the remainder of a division operation. ### Syntax ```python number % 2 == 0 ``` * If `number % 2` evaluates to `0`, the number is **even** (returns `True`). * If `number % 2` evaluates to `1` (or any non-zero value), the number is **odd** (returns `False`). ### Code Example ```python def is_even(number): """ Returns True if the number is even, False otherwise. """ return number % 2 == 0 # Test cases num1 = 4 num2 = 7 # Check num1 if is_even(num1): print(f"{num1} is even") else: print(f"{num1} is not even") # Check num2 if is_even(num2): print(f"{num2} is even") else: print(f"{num2} is not even") ``` ### Output ```text 4 is even 7 is not even ``` ### Code Explanation * **`is_even(number)` Function**: This function accepts a single parameter `number` and evaluates the expression `number % 2 == 0`. If the remainder of `number` divided by `2` is `0`, it returns `True`; otherwise, it returns `False`. * **Conditional Check**: We pass the variables `num1` (4) and `num2` (7) into the function. The `if-else` block prints the corresponding message based on the boolean return value. --- ## 2. The Optimized Approach: Bitwise AND Operator (`&`) For performance-critical applications, you can use the bitwise AND operator (`&`). In binary representation, all odd numbers have their least significant bit (the rightmost bit) set to `1`, while all even numbers have it set to `0`. By performing a bitwise AND operation with `1`, we can instantly determine if a number is even. ### Syntax ```python (number & 1) == 0 ``` ### Code Example ```python def is_even_bitwise(number): # If the last bit is 0, the number is even return (number & 1) == 0 # Test the bitwise function print(is_even_bitwise(10)) # Output: True print(is_even_bitwise(15)) # Output: False ``` *Note: While bitwise operations are slightly faster at the hardware level, the standard modulo operator (`%`) is generally preferred in Python for its superior readability.* --- ## 3. Handling Edge Cases When writing robust Python code, you should consider how your even-check logic handles different data types and negative values. ### Negative Integers Both the modulo (`%`) and bitwise (`&`) methods work perfectly with negative integers in Python. ```python print(is_even(-6)) # Output: True print(is_even(-3)) # Output: False ``` ### Floating-Point Numbers Technically, the concept of "even" and "odd" applies only to integers. If you pass a float to the modulo operator, Python will still evaluate it, which might lead to unexpected logical results. ```python print(is_even(4.0)) # Output: True (4.0 % 2 is 0.0) print(is_even(4.2)) # Output: False ``` To make your function type-safe, you can validate that the input is an integer: ```python def is_even_safe(number): # Ensure the input is an integer if not isinstance(number, int): raise TypeError("Input must be an integer.") return number % 2 == 0 # Example usage try: print(is_even_safe(4.2)) except TypeError as e: print(e) # Output: Input must be an integer. ``` --- ## Summary | Method | Python Expression | Best Used For | Readability | | :--- | :--- | :--- | :--- | | **Modulo Operator** | `number % 2 == 0` | General use cases, standard Pythonic code | High | | **Bitwise Operator** | `(number & 1) == 0` | Low-level optimization, competitive programming | Medium |
← Python Fibonacci SequencePython Sum Numbers β†’