• Home
  • Chemistry
  • Astronomy
  • Energy
  • Nature
  • Biology
  • Physics
  • Electronics
  • Python Code: Checking Numbers within a Range (1-100) Against 50
    ```python

    def check_number():

    """Reads a number from the user and checks if it's greater than, less than, or equal to 50."""

    while True:

    try:

    number = int(input("Enter a number between 1 and 100: "))

    if 1 <= number <= 100:

    break

    else:

    print("Invalid input. Please enter a number between 1 and 100.")

    except ValueError:

    print("Invalid input. Please enter a number.")

    if number > 50:

    print(f"{number} is greater than 50.")

    elif number < 50:

    print(f"{number} is less than 50.")

    else:

    print(f"{number} is equal to 50.")

    Run the function

    check_number()

    ```

    Explanation:

    1. Function Definition: The code defines a function called `check_number()` to encapsulate the logic.

    2. Input Validation Loop:

    - `while True:` creates an infinite loop until a valid number is entered.

    - `try:` attempts to convert the user's input to an integer.

    - `except ValueError:` handles cases where the user input is not an integer.

    - `if 1 <= number <= 100:` checks if the number is within the range 1 to 100.

    - If the input is valid, the loop `break`s.

    3. Comparison and Output:

    - `if number > 50:` checks if the number is greater than 50.

    - `elif number < 50:` checks if the number is less than 50.

    - `else:` handles the case where the number is equal to 50.

    - An appropriate message is printed based on the comparison result.

    4. Function Call: The `check_number()` function is called to execute the algorithm.

    How it works:

    The code first prompts the user to enter a number. It then validates the input to ensure it's an integer between 1 and 100. Once a valid number is obtained, it compares the number to 50 and prints the corresponding result (greater than, less than, or equal to 50).

    Science Discoveries © www.scienceaq.com