Odd or Even Number Checker in Python

 

Python Program to Determine if a Number is Odd or Even

This Python program determines whether a given number is odd or even. The program structure is explained below along with the code and documentation.

Program Structure and Explanation

  1. Input: The program takes an integer input from the user.
  2. Condition Check: It checks if the number is divisible by 2 using the modulus operator (%).
  3. Output: Based on the condition check, it prints whether the number is odd or even.

Python Code with Documentation


"""
Function to determine if a number is odd or even

The function uses the modulus operator to check if the number is divisible by 2.
If the number is divisible by 2 with no remainder, it is even.
If there is a remainder, it is odd.

Args:
    num (int): The number to be checked.

Returns:
    str: A string stating whether the number is odd or even.
"""

def check_odd_even(num):
    if num % 2 == 0:
        return f"{num} is an even number."
    else:
        return f"{num} is an odd number."

def main():
    # Prompt user for input
    try:
        num = int(input("Enter a number: "))
        result = check_odd_even(num)
        print(result)
    except ValueError:
        print("Please enter a valid integer.")

if __name__ == "__main__":
    main()

Explanation of the Code

  • Function Definition: The check_odd_even function is defined to take an integer input and check if it is odd or even.
  • Modulus Operator: The modulus operator (%) is used to check the remainder when the number is divided by 2.
  • Return Statement: Based on the result of the modulus operation, a string is returned indicating if the number is odd or even.
  • Main Function: The main function is the entry point of the program where user input is taken and the check_odd_even function is called.
  • Exception Handling: A try-except block is used to handle cases where the user input is not a valid integer.

 

Leave a Reply

Your email address will not be published. Required fields are marked *