Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading