【问题标题】:Basic Error Capture - for inputs - Python [closed]基本错误捕获 - 用于输入 - Python [关闭]
【发布时间】:2016-06-18 05:02:09
【问题描述】:

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

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

如您所见,如果我有大量来自用户的输入,这将占用大量空间。任何更好的建议将不胜感激。

【问题讨论】:

  • 有没有办法可以设置它以确保数字介于某物之间,例如确保“数字 1”介于 0 和 1 之间?
  • 你可能不会得到太多帮助,因为任何能给出聪明解决方案的人都是“书呆子”。编辑:删除该评论的好电话。
  • 重复任务,考察函数的使用
  • @PortableGibbon 我在 StackOverflow 上帮助有编程问题的人。您可能应该花时间阅读该网站的help page,因为您似乎在这里运气不佳。

标签: python error-handling


【解决方案1】:

这会有帮助吗?

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)

按照上面的建议,将它改编成一个函数也是一个好主意。 问候

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    • 2013-11-07
    • 2015-07-09
    • 2020-04-03
    相关资源
    最近更新 更多