【问题标题】:How to redo an input if user enters invalid answer如果用户输入无效答案,如何重做输入
【发布时间】:2015-09-13 19:55:53
【问题描述】:

我是编程新手,我想知道如果用户输入无效数据,我该如何重复输入部分。

我希望应用程序只重复输入部分,而不是重新运行函数并让用户重新输入所有内容。

我的猜测是我必须将“return main()”更改为其他内容。

condition = input("What is the condition of the phone(New or Used)?")
if condition not in ["New", "new", "Used", "used"]:
    print("Invalid input")
    return main()

gps = input("Does the phone have gps(Yes or No)?")
if gps not in ["Yes", "yes", "No", "no"]:
    print("Invalid input")
    return main()

【问题讨论】:

  • 看看while loop。注意:在示例中,它使用raw_input(),即python 2.7。如果你有python 3.4,你应该使用input()

标签: python input


【解决方案1】:

您可以创建一个方法来循环检查它:

def check_input(values,  message):
    while True:
        x = input(message) 
        if x in values:
            return x
        print "invalid values, options are "   + str(values) 

【讨论】:

    【解决方案2】:

    您可以概括代码以使用消息提示和验证功能:

    def validated_input(prompt, validate):
        valid_input = False
        while not valid_input:
            value = input(prompt)
            valid_input = validate(value)
        return value
    

    例如:

    >>> def new_or_used(value):
    ...     return value.lower() in {"new", "used"}
    
    >>> validate_input("New, or used?", new_or_used)
    

    或者,更简单,但不太灵活,传入有效值:

    def validated_input(prompt, valid_values):
        valid_input = False
        while not valid_input:
            value = input(prompt)
            valid_input = value.lower() in valid_values
        return value
    

    并使用:

    >>> validate_input("New, or used?", {"new", "used"})
    

    您甚至可以使用有效值来创建输入提示:

    def validated_input(prompt, valid_values):
        valid_input = False
        while not valid_input:
            value = input(prompt + ': ' + '/'.join(valid_values))
            valid_input = value.lower() in valid_values
        return value
    

    提示:

    >>> validate_input("What is the condition of the phone?", {"new", "used"})
    What is the condition of the phone?: new/used
    

    【讨论】:

      【解决方案3】:

      这是关于Control Flows 的好读物。

      在您的情况下,您也可以使用strip()lower() 进行用户输入。

      >>> 'HeLLo'.lower()
      'hello'
      >>> ' hello   '.strip()
      'hello'
      

      这里是 Python 3 的解决方案:

      while True:
          condition=input("What is the condition of the phone(New or Used)?")
          if condition.strip().lower() in ['new', 'used']:
              break
          print("Invalid input")
      
      while True:
          gps=input("Does the phone have gps(Yes or No)?")
          if gps.strip().lower() in ['yes','no']:
              break
          print("Invalid input")
      

      【讨论】:

      • 不要这样写。它让你消极思考,并重复代码。如果输入良好,请写while Truebreak
      • 我总是消极思考。它有什么问题? :-) 但我同意它会产生重复的代码,让我更新我的答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-15
      • 1970-01-01
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-07
      • 1970-01-01
      相关资源
      最近更新 更多