基本错误捕获 - 用于输入 - Python

时间:2016-03-04 12:43:53

标签: python error-handling

我正在尝试错误捕获由用户输入设置的变量。到目前为止,我已经做到了这一点,但是如果有更简单或更有效的方法可以徘徊:

 while number1error == 1:
        try:
            number1 = float(input("Please enter the value of number1"))
            break
        except ValueError:
            print("Please enter an integer")

正如您所看到的,如果我从用户那里获得了大量输入,这将占用大量空间。任何更好的建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

这会有帮助吗?

totalReTries = 10
acquiredValue = None
PROMPT_MESSAGE = "Please enter the valid value: "
typeOfInteredData = float
rangeOfData = range(10, 20)

for currentRetry in range(1, totalReTries):

    print "Attempt %d of %d" % (currentRetry, totalReTries)
    try:
        acquiredValue = input(PROMPT_MESSAGE)
    except ValueError:
        print("Incorrect data format. Please try again.")
        continue

    if type(acquiredValue) != typeOfInteredData:
        print "Incorrect data type. Please try again."
        continue
    elif not acquiredValue in rangeOfData:
        print "Incorrect data Range. Please try again."
        continue
    break

if not acquiredValue:
    print "ERROR: Failed to get a correct value"
else:
    print "The acquired value is: " + str(acquiredValue)

如上所述,将其改编成一个函数也是一个好主意。 此致