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.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)