Scrollable Nav Bar

Python program to check if a number is even or odd

Python program to check if a number is even or odd: Given an integer, determine whether it is even or odd and print the result. A number is even when it is divisible by 2 (no remainder). Otherwise it is odd.


Using a fixed value

In this approach we assign a fixed integer value to the variable n and check its parity using the modulus operator %.

# Using a fixed value
n = 47

if n % 2 == 0:
    print(f"{n} is even")
else:
    print(f"{n} is odd")

Output

Explanation: % gives the remainder after division. If n % 2 == 0 the number is even.


Using user input

This version reads a number from the user, converts it to an integer, then checks parity.

# Using user input
n = int(input("Enter an integer: "))

if n % 2 == 0:
    print(f"{n} is even")
else:
    print(f"{n} is odd")

run


Using a function (reusable)

Wrap the logic in a function so you can reuse it in larger programs.

def is_even(n: int) -> bool:
    """Return True if n is even, False otherwise."""
    return n % 2 == 0

# Example usage
num = int(input("Enter an integer: "))
print(f"{num} is {'even' if is_even(num) else 'odd'}")

Using bitwise operator (fast & concise)

Because even numbers have their least significant bit 0, you can check parity with n & 1.

n = int(input("Enter an integer: "))

if n & 1:
    print(f"{n} is odd")
else:
    print(f"{n} is even")

Explanation: n & 1 evaluates to 1 for odd numbers and 0 for even numbers.


One-liner

n = int(input())
print(f"{n} is {'even' if n % 2 == 0 else 'odd'}")

Notes and best practices

  • Ensure you convert user input to int (e.g., int(input())) before checking parity.
  • If the input can be non-integer (like 12.5 or text), validate or handle exceptions using try/except.
  • For negative integers the same rules apply: -4 % 2 == 0 so -4 is even.

Example with input validation

try:
    n = int(input("Enter an integer: "))
except ValueError:
    print("Please enter a valid integer.")
else:
    print(f"{n} is {'even' if n % 2 == 0 else 'odd'}")

Output :