Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Functions

Function to check if number is even or odd - Python Program

Example 1 :

def check_even_odd(num): """Check if a number is even or odd.""" return "Even" if num % 2 == 0 else "Odd" print(check_even_odd(7))

Output

 
OUTPUT  :
Odd

Example 2 : Advanced Program

def check_even_odd(number): """ Checks if a given number is even or odd. Args: number: An integer to be checked. Returns: A string indicating whether the number is "Even" or "Odd". """ if number % 2 == 0: return "Even" else: return "Odd" # Get input from the user num = int(input("Enter an integer: ")) # Call the function and print the result result = check_even_odd(num) print(f"The number {num} is {result}.") # Example usage with specific numbers print(f"The number 4 is {check_even_odd(4)}.") print(f"The number 7 is {check_even_odd(7)}.")

Output

 
OUTPUT  :
Enter an integer: 21
The number 21 is Odd.
The number 4 is Even.
The number 7 is Odd.

Explanation

The program defines a function named check_even_odd that takes one argument, number. Inside the function, the modulo operator (%) is used to determine the remainder when the number is divided by 2.

  • If the remainder is 0, it means the number is perfectly divisible by 2, and therefore, it is an "Even" number.
  • If the remainder is not 0 (it will be 1 for positive integers), it means the number is not perfectly divisible by 2, and therefore, it is an "Odd" number.

The function returns the string "Even" or "Odd" based on this check. The main part of the program prompts the user to enter an integer, calls the check_even_odd function with the entered number, and then prints the result in a user-friendly format. Additionally, two examples with fixed numbers (4 and 7) are included to demonstrate the function's behavior.