【问题标题】:Try-Except block - Did I do this correctly?Try-Except 块 - 我做对了吗?
【发布时间】:2020-03-26 16:08:18
【问题描述】:

我们正在学习异常处理。我做对了吗? ValueError 是用于捕获正在键入的字符串而不是数字的正确异常吗?我尝试使用 TypeError,但它没有捕获异常。

另外,有没有更有效的方法来捕获我的四个输入中的每个异常?这里的最佳做法是什么?

#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

【问题讨论】:

  • 它在运行时是否按您预期的方式工作?
  • 好点。是的,它按预期工作。然而,我还是个新手,发现自己运行的代码我认为可以按预期工作,但它仍然写得不正确。无论如何,它似乎确实完美无缺。

标签: python exception try-except


【解决方案1】:

这里你正在体验所谓的,WET 代码 Write Everything Twice,我们尝试编写 DRY 代码,即不要重复自己。

在您的情况下,您应该做的是创建一个名为 float_input 的函数,使用您的 try except 块并为每个变量赋值调用它。

def float_input(msg):
    while True:
        try:
            return float(input(msg))
        except ValueError:
            pass


range_lower = float_input('Enter your lower range: ')
...

【讨论】: