简体   繁体   中英

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

Here you are experiencing what is called, WET code Write Everything Twice, we try to write DRY code, ie 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: ')
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM