检查用户输入的问题(Python)

时间:2013-12-30 23:48:03

标签: python error-handling user-input

我正在尝试检查用户输入是否为整数且lower_bound是否大于或等于零。我也试图检查upper_bound是否大于lower_bound。这是我的代码:

while True:

    try:

        lower_bound = int(input("What is the lower bound for x >= 0 (inclusive?)"))

    except ValueError:

        print("Lower bound is not an integer.")
        continue

    else:

        if lower_bound < 0:

            print("Lower bound cannot be less than zero.")
            continue   
    try:

        upper_bound = int(input("What is the upper bound (inclusive)?"))
        break

    except ValueError:

        print("Upper bound is not an integer.")

    else:

        if (upper_bound < lower_bound):

            print("The upper bound cannot be less than the lower bound.")
            continue

对于lower_bound工作的用户输入的检查是正确的,因为检查upper_bound是一个整数。但是,如果upper_bound小于lower_bound,则不返回错误 - 为什么会这样?

此外,我觉得我的代码必须非常冗长 - 我怎么能让所有这些错误检查更简洁?

谢谢,

1 个答案:

答案 0 :(得分:2)

        upper_bound = int(input("What is the upper bound (inclusive)?"))
        break

你为什么要打破?此break将立即结束循环,跳过upper_bound < lower_bound检查。在最终检查后移动break,因此只有在所有检查通过后才会中断。