【问题标题】:How can I make a Validation Try and Except Error for this?如何为此进行验证尝试并排除错误?
【发布时间】:2015-11-24 20:37:43
【问题描述】:

我有如下所示的代码,我想创建一个函数,它有一个 try 和 except 错误,所以当你输入 1、2 或 3 以外的任何内容时,它会让你重新输入它。下面是询问您年龄的行。

    Age = input("What is your age? 1, 2 or 3: ")

以下是我迄今为止尝试实现的目标。

   def Age_inputter(prompt=' '):
        while True:
            try:
                return int(input(prompt))
            except ValueError:
                print("Not a valid input (an integer is expected)")

有什么想法吗?

【问题讨论】:

标签: python function validation try-catch except


【解决方案1】:

在返回之前添加一个检查,如果检查失败则引发:

def Age_inputter(prompt=' '):
        while True:
            try:
                age = int(input(prompt))
                if age not in [1,2,3]: raise ValueError
                return age
            except ValueError:
                print("Not a valid input (an integer is expected)")

【讨论】:

    【解决方案2】:

    这可能有效:

    def Age_inputter(prompt=' '):
        while True:
            try:
                input_age = int(input(prompt))
                if input_age not in [1, 2, 3]:
                    # ask the user to input his age again...
                    print 'Not a valid input (1, 2 or 3 is expected)'
                    continue
                return input_age
            except (ValueError, NameError):
                print 'Not a valid input (an integer is expected)'
    

    【讨论】:

    • 我如何将它链接到 Age = input("你的年龄是多少?1、2 或 3:") 这样它才能工作?
    • @EDoggyDog,你只需要写 Age = Age_inputter('What is your age? 1, 2 or 3:')
    猜你喜欢
    • 2016-10-31
    • 2019-02-04
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-28
    • 2015-05-17
    • 1970-01-01
    相关资源
    最近更新 更多