Even or Odd Program in Python

Answered using GPT-4o mini by AI Answer Generator

Question:

Program 1: “Even or Odd” The intent of this program is to allow a user to enter integer inputs, and after each input it immediately outputs a formatted statement as to whether the input is even of odd. The user must be notified of a sentinel value. The user will continue to be prompted to enter an integer until the sentinel value is entered at which point the program will stop. The functionality must be accomplished using a while loop and include this: Write in python

  1. The first output should be a program header as described above like: ########## Program #1 – Even or Odd ###########
  2. a user prompt for either an integer input or sentinel value
  3. a formatted output statement of whether that number is even or odd. • You will need to select a sentinel.
Answer:

Here's a Python program that meets the requirements you've outlined for the "Even or Odd" program. The program will prompt the user to enter integers and will determine if each input is even or odd until the user enters a sentinel value to stop the program.

# Program Header
print("########## Program #1 – Even or Odd ###########")

# Sentinel value
sentinel = -1  # You can choose any integer as a sentinel value

while True:
    # User prompt for input
    user_input = input(f"Please enter an integer (or {sentinel} to exit): ")

    # Try to convert the input to an integer
    try:
        number = int(user_input)
    except ValueError:
        print("Invalid input. Please enter a valid integer.")
        continue

    # Check for sentinel value
    if number == sentinel:
        print("Exiting the program.")
        break

    # Determine if the number is even or odd
    if number % 2 == 0:
        print(f"{number} is even.")
    else:
        print(f"{number} is odd.")

Explanation:

  1. Program Header: The program starts with a header that clearly states the program's purpose.
  2. Sentinel Value: The sentinel value is set to -1, which the user can enter to exit the program.
  3. User Input: The program prompts the user to enter an integer or the sentinel value.
  4. Input Validation: The program checks if the input can be converted to an integer. If not, it prompts the user again.
  5. Even or Odd Check: If the input is not the sentinel value, the program checks if the number is even or odd and prints the appropriate message.
  6. Loop: The program continues to prompt for input until the sentinel value is entered.