【问题标题】:Multiple Error Handling on PythonPython 上的多重错误处理
【发布时间】:2014-07-15 19:28:30
【问题描述】:

我想知道如何处理 python 上的多个错误。

例如:

用户输入一个介于 0 和 9 之间的整数。如果该整数超出范围,则程序会这样说并要求另一个输入,直到获得有效输入。如果输入不是整数,那么程序会说它是无效输入并要求另一个输入,直到获得有效输入。最后,如果没有提供输入,那么程序会说需要一个输入,并要求另一个输入,直到获得一个有效的输入。对于单个输入变量,必须区分这三个错误。

提前感谢您的帮助

【问题讨论】:

  • 你试过if声明吗?

标签: python-3.x try-except


【解决方案1】:

尝试类似的方法:

wrong = True
while wrong:
        num = input("Enter a number between 0 and 9: ")
        if not num:
                print("Please enter valid input.")
                continue

        try:
                num = int(num)
        except ValueError:
                print("Please enter valid input.")
                continue

        if num < 0 or num > 9:
                print("Please enter a number between 0 and 9.")
                continue

        wrong = False

print(num)

运行如下:

bash-3.2$
Enter a number between 0 and 9: 
Please enter valid input.
Enter a number between 0 and 9: 
Please enter valid input.
Enter a number between 0 and 9: hhello
Please enter valid input.
Enter a number between 0 and 9: 90
Please enter a number between 0 and 9.
Enter a number between 0 and 9: -2324
Please enter a number between 0 and 9.
Enter a number between 0 and 9: aisjdo93rwfeljks
Please enter valid input.
Enter a number between 0 and 9: 5
5

【讨论】:

    【解决方案2】:

    这样的事情可能会有所帮助:

    valid = False
    while not valid:
        in_val = input("Enter an integer: ")
        if not in_val:
            print("No input was given, please try again.")
            continue
    
        try:
            in_num = int(in_val)
    
            if in_num < 0 or in_num > 9:
                print("The value entered is out of the valid range (0-9).")
                continue
            valid = True
        except ValueError:
            print("The value entered was not a number, try again.")
            continue
    

    【讨论】:

    • 我不认为 OP 询问命令行选项很清楚,所以这可能是一个很大的矫枉过正。
    【解决方案3】:

    如果您想根据多个条件验证用户输入并在其中任何一个失败时继续请求新输入,您可能希望循环一直持续到获得有效结果:

    result = None
    while result is None:
        input_str = input("Enter an integer between 0 and 9:")
        if input_str == "":
            print("An empty input is not valid.")
        else:
            try:
                result = int(input_str)
                if not 0 <= result <= 9:
                    print("That number out of bounds.")
                    result = None
            except ValueError:
                print("That is not an integer.")
    
    # do stuff with result here
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-18
      • 1970-01-01
      • 2015-09-02
      • 2016-08-12
      • 1970-01-01
      • 2010-10-27
      • 2014-10-15
      • 1970-01-01
      相关资源
      最近更新 更多