Search code examples
pythonexceptiontry-except

Try-Except block - Did I do this correctly?


We are learning exception handling. Did I do this correctly? Is ValueError the correct exception to use to catch strings being typed instead of numbers? I tried to use TypeError, but it doesn't catch the exception.

Also, is there a more efficient way to catch each exception in my four inputs? What is best practice here?

#Ask user for ranges. String inputs are not accepted and caught as exceptions. While loop repeats asking user for input until a float number is input.
while True:
    try:
        rangeLower = float(input("Enter your Lower range: "))
    except ValueError:
        print("You must enter a number!")
    else:
        #Break the while-loop
        break
while True:
    try:
        rangeHigher = float(input("Enter your Higher range: "))
    except ValueError:
        print("You must enter a number!")
    else:
        #Break the while-loop
        break
#Ask user for numbers. String inputs are not accepted and caught as exceptions. While loop repeats asking user for input until a float number is input.
while True:
    try:
        num1 = float(input("Enter your First number: "))
    except ValueError:
        print("You must enter a number!")
    else:
        #Break the while-loop
        break
while True:
    try:
        num2 = float(input("Enter your Second number: "))
    except ValueError:
        print("You must enter a number!")
    else:
        #Break the while-loop
        break

Solution

  • Here you are experiencing what is called, WET code Write Everything Twice, we try to write DRY code, i.e. Don't Repeat Yourself.

    In your case what you should do is create a function called float_input as using your try except block and calling that for each variable assignment.

    def float_input(msg):
        while True:
            try:
                return float(input(msg))
            except ValueError:
                pass
    
    
    range_lower = float_input('Enter your lower range: ')
    ...