Search code examples
pythonexception

What is a better way to allow no user input while also preventing non-number inputs


def prompt_for_angles(angle_name: str) -> float:
    try:
        angle: float or None = float(input(f"Angle for {angle_name}: "))
        while not (0 < angle < 180):  # while input is NOT correct
            print("Invalid. Please enter an angle between 0 and 180")
            angle: float or None = float(input(f"Angle for {angle_name}: "))
    except ValueError:  # nothing is entered, acceptable
        print("value error")
        angle = unknown
    return angle

I am making an application that lets a user input a triangle's known angles and side lengths, and depending on the unknown side, calculate that length or angle. I want to maintain the ability for the user to enter nothing and save that angle as unknown (0) while also preventing the user from inputting non-numbers. What is the best way to restructure this so I can do both?

This try except block works correctly when it comes to no input but it also catches all other value errors like characters and symbols.


Solution

  • Check for an empty input before converting the input to float. This way you can distinguish it from other invalid inputs.

    def prompt_for_angles(angle_name: str) -> float:
        while True:
            num = input(f"Angle for {angle_name}: ").strip()
            if num == "":
                return unknown
            try:
                angle: float = float(num)
                if 0 <= angle <= 180:
                    return angle
            except ValueError:
                pass
            print("Invalid. Please enter an angle between 0 and 180")